且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在MySQL中,"REPLACE"和"INSERT ... ON DUPLICATE KEY UPDATE"之间有什么实际区别?

更新时间:2023-02-18 11:47:06

REPLACE在内部执行删除操作,然后执行插入操作.如果您有指向该行的外键约束,则可能会导致问题.在这种情况下,REPLACE可能会失败或更糟:如果将外键设置为级联删除,则REPLACE将导致其他表中的行被删除.即使在REPLACE操作之前和之后都满足约束条件,也会发生这种情况.

REPLACE internally performs a delete and then an insert. This can cause problems if you have a foreign key constraint pointing at that row. In this situation the REPLACE could fail or worse: if your foreign key is set to cascade delete, the REPLACE will cause rows from other tables to be deleted. This can happen even though the constraint was satisfied both before and after the REPLACE operation.

使用INSERT ... ON DUPLICATE KEY UPDATE可以避免此问题,因此是首选.

Using INSERT ... ON DUPLICATE KEY UPDATE avoids this problem and is therefore prefered.