MySQL: Update multiple columns if their value equals to [duplicate]

核能气质少年 提交于 2021-02-10 12:13:31

问题


I would like to know if there's a 'short' way (single query) to update certain columns, if their value equals to an integer.

Let's say that my table looks like this:

+------------+----+----+----+----+
| customerID | v0 | v1 | v2 | v3 |
+------------+----+----+----+----+
|          1 |  3 |  3 |  2 |  1 |
+------------+----+----+----+----+

and I would like to set all the values of integer 3 (except customerID) to 0 - so the query will update column v0 and v1.


回答1:


You can do this with a bunch of case statements:

UPDATE my_table
SET    v0 = CASE v0 WHEN 3 THEN 0 ELSE v0 END,
       v1 = CASE v1 WHEN 3 THEN 0 ELSE v1 END,
       v2 = CASE v2 WHEN 3 THEN 0 ELSE v2 END,
       v3 = CASE v3 WHEN 3 THEN 0 ELSE v3 END
WHERE  3 IN (v0, v1, v2, v3)



回答2:


Mureinik, has already mentioned one useful way, another way is using If statement

Update my_table
set v0= If(v0=3,0,v0),
    v1= If(v1=3,0,v1),
    v2= If(v2=3,0,v2),
    v3= If(v3=3,0,v3)
where 3 In (v0, v1, v2, v3)

here is the DEMO.



来源:https://stackoverflow.com/questions/34697997/mysql-update-multiple-columns-if-their-value-equals-to

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