INSERT INTO … ON DUPLICATE UPDATE all values

若如初见. 提交于 2019-12-24 11:28:04

问题


Can I safely update all values like this:

INSERT INTO tbl_name SET `a`=:a, `b`=:b, ... `z`=:z
ON DUPLICATE KEY UPDATE
`a`=VALUES(`a`), `b`=VALUES(`b`), ... `z`=VALUES(`z`);

I have tried it, and it works. But it's tested only on one innodb table.

I have found these related questions 1, 2, 3 but there's no mention that updating ALL columns (unique and/or pk) is 100% safe.

It doesn't create any error on updating PK with same value.
It doesn't create any error on updating Unique col with same value.

So, is it 100% safe to use? If not, what are corner cases, when it breaks?

--------- edit -------------
added ... up to z col


回答1:


INSERT INTO … ON DUPLICATE KEY UPDATE works this way:

  • it attempts to insert a row as usual
  • if any constraint violation in any column occurs, it executes the UPDATE statement instead on the existing row with which the INSERT statement clashed

That simply means if the UPDATE statement alone would be successful, its ON DUPLICATE KEY UPDATE equivalent will also work. That means you obviously can't violate any constraints in the UPDATE statement either, or the whole thing will fail (e.g. trying to set a value on a UNIQUE column which already exists in another row).

If you set the same value on the same column again, that's essentially a no-op. The value in the column doesn't change and therefore also can't cause any errors (let's assume you don't have any really funky BEFORE UPDATE triggers which can misbehave). The number of columns is irrelevant here, you can change as many or as few in one statement as you like.



来源:https://stackoverflow.com/questions/32179878/insert-into-on-duplicate-update-all-values

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