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

后端 未结 12 2481
孤街浪徒
孤街浪徒 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:03

    INSERT...ON DUPLICATE KEY UPDATE is prefered to prevent unexpected Exceptions management.

    This solution works when you have **1 unique constraint** only

    In my case I know that col1 and col2 make a unique composite index.

    It keeps track of the error, but does not throw an exception on duplicate. Regarding the performance, the update by the same value is efficient as MySQL notices this and does not update it

    INSERT INTO table
      (col1, col2, col3, col4)
    VALUES
      (?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE
        col1 = VALUES(col1),
        col2 = VALUES(col2)
    

    The idea to use this approach came from the comments at phpdelusions.net/pdo.

提交回复
热议问题