Question

I would like to substract 1 from SEVERAL elements in a table if they are not equal to 0.

Code for one element

UPDATE `database` SET a1=a1-1 WHERE a1!='0' AND username='bob';

I want to do the same thing on the same command for several elements, a2, a3... (username stay the same for all elements)

Thank you

Was it helpful?

Solution

You're probably looking for conditionals within your set expressions. This can be achieved with the keyword CASE:

UPDATE 'database' 
SET
  a1 = CASE WHEN a1 != 0 THEN (a1 - 1) END,
  a2 = CASE WHEN a2 != 0 THEN (a2 - 1) END
WHERE
  username='bob';

Be sure to understand the principles of the sql update syntax which consists basically of a single UPDATE ... SET ... [WHERE] pattern.

Hint: I'm pretty sure your a1,a2,a3,.. fields are of type integer, so - unlike in your code example - the value to check must not put into quotes!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top