MySQL does not decrease when it is 0

I have

UPDATE topic SET liked = liked - 1 WHERE id='$id' 

It does not decrease if liked 0 .

What do I need to do to reduce the liked field when liked like 0 ?

Note: it works when it is not 0.

Edit: liked - int.

+4
source share
3 answers

Do you want to have a floor of zero?

 UPDATE topic SET liked = liked - 1 WHERE id='$id' AND liked > 0; 

If you need negative numbers, you need a SIGNED datatype . However, you need to know the limitations to avoid errors. See "Out of Range and Overflow Processing"

So, the assumption that I liked it is changed to SIGNED TINYINT ...

 UPDATE topic SET liked = liked - 1 WHERE id='$id' AND liked > -128; 
+4
source

You must set the liked column to SIGNED.

eg.

 ALTER TABLE `tbl` CHANGE `liked` `liked` INT(10) SIGNED 
+2
source

If you use a UNSIGNED integer, it cannot fall below 0, but if I got u right - can you decrease the value when it is below 0? If so, have you tried using values? Maybe the problem is that MySQL is 0 to NULL? Try it like this:

 `liked` = (`liked` - 1) 
+1
source

Source: https://habr.com/ru/post/1388146/


All Articles