dongyuchen9276 2010-01-06 10: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 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 (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)

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

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加