MySQL 中的多次更新

2021-11-20 00:00:00 sql-update sql mysql

我知道您可以一次插入多行,有没有办法在 MySQL 中一次更新多行(如在一个查询中)?

I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?

例如我有以下内容

Name   id  Col1  Col2
Row1   1    6     1
Row2   2    2     3
Row3   3    9     5
Row4   4    16    8

我想将以下所有更新合并为一个查询

I want to combine all the following Updates into one query

UPDATE table SET Col1 = 1 WHERE id = 1;
UPDATE table SET Col1 = 2 WHERE id = 2;
UPDATE table SET Col2 = 3 WHERE id = 3;
UPDATE table SET Col1 = 10 WHERE id = 4;
UPDATE table SET Col2 = 12 WHERE id = 4;

推荐答案

是的,这是可能的 - 您可以使用 INSERT ... ON DUPLICATE KEY UPDATE.

Yes, that's possible - you can use INSERT ... ON DUPLICATE KEY UPDATE.

使用您的示例:

INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12)
ON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2);

相关文章