2

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
mexikanoZ
  • 81
  • 11

2 Answers2

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)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

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.

Community
  • 1
  • 1
void
  • 7,760
  • 3
  • 25
  • 43