dongyuchen9276 2010-01-06 02:14
浏览 212
已采纳

在执行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. :)

Thanks.

  • 写回答

1条回答 默认 最新

  • duanre1891 2010-01-06 02: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 (http://dev.mysql.com/doc/refman/5.1/en/replace.html) or the ON DUPLICATE KEY UPDATE construct (http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部