MySql - ON DUPLICATE KEY INSERT

前端 未结 2 640
迷失自我
迷失自我 2021-01-05 01:38

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

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-05 01:53

    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;
    

提交回复
热议问题