简体   繁体   中英

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?

Use 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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