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

2022-01-09 00:00:00 sql replace insert mysql

我需要的是使用特定键设置记录的所有字段的值(键实际上是复合键),如果还没有具有这样键的记录,则插入记录.

What I need is to set the values of all the fields of a record with a particular key (the key is composite actually), inserting the record if there is no record with such a key yet.

REPLACE 似乎打算做这项工作,但同时它的手册页建议INSERT ... ON DUPLICATE KEY UPDATE.

我应该更好地选择它们中的哪一个?为什么?

What of them should I better choose and why?

我想到的 REPLACE 的唯一副作用"是它会增加自动增量值(幸运的是我不使用任何值)而 INSERT ... ON DUPLICATE KEYUPDATE 可能不会.还有哪些实际差异需要考虑?在哪些特定情况下,REPLACE 可以优于 INSERT ... ON DUPLICATE KEY UPDATE,反之亦然?

The only "side effect" of REPLACE that comes into my mind is that it would increment autoincrement values (fortunately I don't use any) while INSERT ... ON DUPLICATE KEY UPDATE probably wouldn't. What are the other practical differences to take in mind? In what particular cases can REPLACE be preferred over INSERT ... ON DUPLICATE KEY UPDATE and vice versa?

推荐答案

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.

相关文章