mysql insert after delete fails because of "duplicate entry"

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.


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

改用UPDATE语句:

UPDATE my_table
SET my_column = my_value
WHERE user_id = some_number

您可以在DELETE后总是尝试COMMIT以确保其完成。

链接地址: http://www.djcxy.com/p/53716.html

上一篇: 促进构建到不同的环境

下一篇: 删除后mysql插入失败,因为“重复条目”