Prevent auto increment on duplicate entry

一世执手 提交于 2020-01-06 03:36:14

问题


I have seen this issue around (See links at bottom) but I can't seem to figure out an answer. The problem is that I insert data on a table with an auto increment ID that is a primary key, and another field with a UNIQUE index to avoid duplicates. This works, but when that happens the ID is incremented, although no data has been stored.

Would it be better to remove the auto increment, and handle it myself, selecting the max(ID)?


At the moment I have tried several strategies to make it work as is, including INSERT IGNORE and INSERT ... ON DUPLICATE KEY UPDATE

My latest try was using the following query:

INSERT INTO
    content(field1, field2)
SELECT(:field1, :field2) FROM DUAL
WHERE NOT EXISTS(
    SELECT field1, field2
    FROM content
    WHERE field1 = :field1
)

Related

  • In MySQL, when there is a "duplicate entry" error, how do I prevent the primary key from auto incrementing?
  • SQL Server - How to insert a record and make sure it is unique

回答1:


Thanks to this question I have been able to fix that error. The problem was that the SELECT(:field1, :field2) shouldn't have the parenthesis. So the query should be:

INSERT INTO
    content(field1, field2)
SELECT :field1, :field2 FROM DUAL
WHERE NOT EXISTS(
    SELECT field1, field2
    FROM content
    WHERE field1 = :field1
)



回答2:


You could just do an ORDER BY :)

UPDATE 'table' 
    SET column_id = column_id+1 
    WHERE column_id > [point where you want a un-occupied key] 
    ORDER BY column_id DESC

mysql executes the where and order by first then your update



来源:https://stackoverflow.com/questions/15588400/prevent-auto-increment-on-duplicate-entry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!