“INSERT IGNORE” vs “INSERT … ON DUPLICATE KEY UPDATE”

后端 未结 12 2506
孤街浪徒
孤街浪徒 2020-11-21 04:30

While executing an INSERT statement with many rows, I want to skip duplicate entries that would otherwise cause failure. After some research, my options appear

12条回答
  •  失恋的感觉
    2020-11-21 05:21

    Adding to this. If you use both INSERT IGNORE and ON DUPLICATE KEY UPDATE in the same statement, the update will still happen if the insert finds a duplicate key. In other words, the update takes precedence over the ignore. However, if the ON DUPLICATE KEY UPDATE clause itself causes a duplicate key error, that error will be ignored.

    This can happen if you have more than one unique key, or if your update attempts to violate a foreign key constraint.

    CREATE TABLE test 
     (id BIGINT (20) UNSIGNED AUTO_INCREMENT, 
      str VARCHAR(20), 
      PRIMARY KEY(id), 
      UNIQUE(str));
    
    INSERT INTO test (str) VALUES('A'),('B');
    
    /* duplicate key error caused not by the insert, 
    but by the update: */
    INSERT INTO test (str) VALUES('B') 
     ON DUPLICATE KEY UPDATE str='A'; 
    
    /* duplicate key error is suppressed */
    INSERT IGNORE INTO test (str) VALUES('B') 
     ON DUPLICATE KEY UPDATE str='A';

提交回复
热议问题