dotcom22
dotcom22

Reputation: 259

Mysql query: decrease value by 1

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?

Upvotes: 8

Views: 12183

Answers (2)

Maxime Lorant
Maxime Lorant

Reputation: 36161

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'

Upvotes: 13

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

Try this one remove single quotes from the column name other it will be treated as string 'my_field-1' or use back-ticks around column name

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

or

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

Upvotes: 7

Related Questions