更新 MySQL 1 列中的多行

2022-01-17 00:00:00 sql-update sql mysql

在 MySQL 中同时更新多行的正确查询是什么?

What is the proper query for updating multiple rows in MySQL at the same time?

我只更新 1 列:

UPDATE example_table SET variable1 = 12 WHERE id=1;
UPDATE example_table SET variable1 = 42 WHERE id=2;
UPDATE example_table SET variable1 = 32 WHERE id=3;
UPDATE example_table SET variable1 = 51 WHERE id=4;

这似乎效率低下,或者如果它是最有效的查询,请告诉我:)

This seems like it may be inefficient, or if it is the most efficient query let me know :)

推荐答案

您可以使用以下案例:

UPDATE example_table
   SET variable1 = CASE id
                     WHEN 1 THEN 12
                     WHEN 2 THEN 42
                     WHEN 3 THEN 32
                     WHEN 4 THEN 51
                   END
 WHERE id BETWEEN 1 AND 4

相关文章