2010-01-06 10:14 阅读 95

在执行INSERT IGNORE时如何在表中找到重复的ID?

I know that when doing a INSERT IGNORE duplicate entries are ignored and errors become warning but here is what I need.

Scenario: We have a table with 2 columns (id, name) where BOTH are UNIQUE and id is PRIMARY KEY.

When you do an INSERT IGNORE on column name it creates the next AUTO_INCREMENT for id (even though it later doesnt exist in your DB, its just skipped) and when you call LAST_INSERT_ID it gives you the that next id. However I need to find the id that caused the query to be ignore. In other words the id of the name that was a duplicate.

Any MySQL/PHP trick is welcomed. :)


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanre1891 duanre1891 2010-01-06 10:41

    I don't think you can extract this information with INSERT IGNORE. Even if the warning text would contain the key value, there are only so many warnings buffered, so you couldn't rely on that.

    I would probably try to rewrite the query so that it avoids inserting a duplicate. You can always detect the keys before hand by doing a

    SELECT id FROM tab WHERE name in ('...value1...',...,'...valueN...')

    Depending on the format of the data you want to insert, and how you are doing the inserts (bulk, or one row at a time) you can do several things to avoid inserting known duplicates.

    If on the other hand you had the idea of extracting the IDs of the would-be duplicates to perform an update for those rows instead, then you should use the REPLACE syntax ( or the ON DUPLICATE KEY UPDATE construct (

    点赞 评论 复制链接分享