MySql - ON DUPLICATE KEY INSERT

ε祈祈猫儿з 提交于 2019-11-30 04:17:11

问题


I understand that there exists INSERT IGNORE and INSERT ... ON DUPLICATE KEY UPDATE. However, when there is a duplicate key, I'd like to do a INSERT to a temporary table to keep a record of the unique key that has been violated, so that I can output it to the user.

Is there any way I can do a ON DUPLICATE INSERT? If it helps, I'm trying to do a bulk insert.


回答1:


With ON DUPLICATE KEY UPDATE, you cannot insert into another table - nor is there an alternative function available.

Two custom/alternative ways you can accomplish this:

  1. Using a stored procedure as outlined in the accepted answer to this question: MySQL ON DUPLICATE KEY insert into an audit or log table

  2. Creating a trigger that logged every INSERT for your table into another table and querying the table full of "logs" for any duplicates.

Something similar to this should work:

CREATE TABLE insert_logs (
    id int not null
);

delimiter |
CREATE TRIGGER insert_logs_trigger BEFORE INSERT ON your_table
    FOR EACH ROW BEGIN
        INSERT INTO insert_logs SET id = NEW.id;
    END;
|

To get a list of the duplicates in the table, you could us:

SELECT id FROM insert_logs HAVING COUNT(id) > 1 GROUP BY id;


来源:https://stackoverflow.com/questions/11940506/mysql-on-duplicate-key-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!