mysql - How to insert ignore MySQL rows into another table and update a field when duplicates found?
问题描述
I'm trying to make a telemarketing campaign management web application. Application user can upload Excel sheets including telephone number + status fields to the application and update the "status" when they are making a call to clients. When an Excel sheet is uploaded, all the data goes to a table called "tp_numb". Then I created "MySQL insert ignore" to copy data from "tp_numb" to a table called "ok_list". I need to update the "status" field in the "ok_list" table when duplicates are found. If duplicates are not found, the data should be inserted into the "ok_list" table.
CREATE TABLE `tp_numb` (
`id` int(11) NOT NULL,
`number` varchar(10) NOT NULL,
`ref_id` int(10) NOT NULL,
`status` int(1) NOT NULL DEFAULT '0',
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `ok_list` (
`id` int(11) NOT NULL,
`tp_numb_id` int(10) NOT NULL,
`number` varchar(10) NOT NULL,
`status` int(2) NOT NULL,
`notes` text,
`status_updated_on` datetime DEFAULT NULL,
`ref_id` int(10) NOT NULL,
`date` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`assign` int(10) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT IGNORE INTO ok_list (tp_numb_id, number, status, ref_id)
SELECT t.id, t.number, t.status, r.ref_id
FROM tp_numb t, reference r
WHERE t.ref_id = r.ref_id;
Above code is the code I have been trying to improve with a function to update the "status" field in the "ok_list" table. Because the status of telephone numbers should be the status according to the last uploaded Excel file. How can I update the status when a duplicate found? How can I insert a record when duplicates are not found?
解决方案
I think you want on duplicate key update
:
INSERT INTO ok_list (tp_numb_id, number, status, ref_id)
SELECT t.id, t.number, t.status, r.ref_id
FROM tp_numb t JOIN
reference r
ON t.ref_id = r.ref_id
ON DUPLICATE KEY UPDATE status = VALUES(status);
Your question supposed that there is only one row for each number. I'm not actually sure which column that is, but you should have a unique constraint/index so it know which row gets updated with the status. I think it is tp_numb_id
, which would be;
create unique index unq_ok_list_tp_numb_id on ok_list(tp_numb_id);
推荐阅读
- javascript - nodejs依次运行数组中定义的作业
- python-3.x - pandas 按该类别的平均值填充空值
- python - 使用poseexplode分解带有索引的嵌套JSON
- javascript - 为什么单击带有 href 的 Rails link_to 锚点到服务器不会产生 DomContentLoaded 事件?
- python - Python 3 - 将可变数量的列表合并为一个
- html - 如何扩展 div 使其从上到下覆盖
- html - 当它成为菜单下拉菜单时,如何删除边框?(角度)
- javascript - 使用 querySelectorAll 从标签的所有属性中提取值
- ios - Kotlin Native 项目中 iOS 上的 libPhonenumber(来自 Google)
- linux - 在 Ubuntu/Linux 中查找准确的物理内存使用情况