Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql query: decrease value by 1

Tags:

mysql

I would like decrease by 1 the value contained inside a field (integer or drop-down). I tried these 3 queries but none of them work as expected:

UPDATE `my_table` SET `my_field` = 'my_field-1' WHERE `other` = '123'

UPDATE `my_table` SET `my_field` = 'my_field' -1 WHERE `other` = '123'

UPDATE `my_table` SET `my_field` = '-1' WHERE `other` = '123'

I searched here and on Google but all solutions I found are similar. Any idea why this doesn't work at my side?

like image 473
dotcom22 Avatar asked Feb 16 '14 16:02

dotcom22


1 Answers

You don't need any quotes.

UPDATE my_table SET my_field = my_field - 1 WHERE `other` = '123'

To understand, it's like a classic affectation in any languages: "I want my_field being equal to my_field (the current value) minus 1.
If you put quotes, it means "I want my_field being equal to the string:

  1. 'my_field-1' (for your first query)
  2. 'my_field' - 1 (which means nothing, at least for me: what the result of a string minus an integer?)
  3. '-1', which will be converted to -1 if your field has the INTEGER signed type.

In some cases (if you have spaces or special characters if your field name), you can surrounded the field name with `backticks`:

UPDATE my_table SET `my_field` = `my_field` - 1 WHERE  other = '123'
like image 71
Maxime Lorant Avatar answered Oct 02 '22 15:10

Maxime Lorant