简体   繁体   English

MySQL:使用不同的条件更新不同的列

[英]MySQL: update different columns with separate conditions

Please how can I update different columns base on different and specific conditions. 请如何根据不同和特定的条件更新不同的列。 For example: 例如:

UPDATE table
SET col1 = val1 WHERE col1 > 2
SET col2 = val2 WHERE col2 > 1

Is is possible to write an SQL UPDATE statement like this Where different columns will be updated base on separate conditions? 是否可以编写这样的SQL UPDATE语句,其中将根据不同的条件更新不同的列?

Use case : case

UPDATE table
    SET col1 = (CASE WHEN col1 > 2 THEN val1 ELSE col1 END),
        col2 = (CASE WHEN col2 > 1 THEN val2 ELSE col2 END);

You can also add WHERE col1 > 2 or col2 > 1 so MySQL does not attempt to update all rows. 您还可以添加WHERE col1 > 2 or col2 > 1这样MySQL不会尝试更新所有行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM