mysql insert after delete fails because of “duplicate entry”

懵懂的女人 提交于 2021-02-18 20:56:19

问题


I have a code with two mysql queries.
DELETE FROM my_table WHERE user_id=some_number
INSERT INTO my_table (user_id, ... ) VALUES(some_number, ...)

The field user_id is unique.

In rare cases the insert fails claiming a duplicate entry occurred. My first instinct leads me to to believe the DELETE didn't finish and now the insert is trying to insert and I'm getting a duplicate entry. Is this possible? How can I avoid this? Might there be a different explanation you can think of?

Update: The reason I'm deleting is because I want to delete all the data that I am not updating / inserting for the first time. Also, I think it is important to state that most of the data remains the same.


回答1:


SET AUTOCOMMIT=0;    
START TRANSACTION;    
DELETE FROM my_table WHERE user_id=some_number;     
INSERT INTO my_table (user_id, ... ) VALUES(some_number, ...); 
commit;



回答2:


Use an UPDATE statement instead:

UPDATE my_table
SET my_column = my_value
WHERE user_id = some_number



回答3:


You could always try a COMMIT after the DELETE to make sure its completed.




回答4:


Why do you DELETE and then INSERT the same user_id and not just UPDATE the row?




回答5:


This happens because the query are treated as two single transaction, so the order of execution is not guaranteed. The effect you are describing is because the insert is processed before delete. You should change the query logic or perform both queries in one single transaction.



来源:https://stackoverflow.com/questions/6777672/mysql-insert-after-delete-fails-because-of-duplicate-entry

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