On my MySQL database, I have a unsigned mediumint column, which I keep incrementing and decrementing its value.
However, I want to be sure that it doesn’t decrement when its value is 0. If I do, the UPDATE will make the value to take the maximum value of mediumint, 16777215.
So, I have this query when decrementing:
UPDATE `counters` SET `received`=IF(CAST(`received`-1 AS SIGNED)>0, `received`-1, 0) WHERE `id`="1234"
This was the only trick I got to work with only one query.
It works very well on MySQL 5.1, but, yesterday I upgraded to MySQL 5.5 and now I get these errors:
BIGINT UNSIGNED value is out of range in '(`db_main`.`counters`.`received` - 1)'
Is there any way to fix this?
Or… is there any other way to make sure, in only one query, that it won’t take the value of “16777215” when subtracting 1 to 0?
EDIT – I could use the WHERE, adding ” AND received > 0″. The thing is that sometimes I want to update two columns at the same time, and if I put all the columns > 0 in the WHERE clause, it won’t update ANY of the columns.
Thank you.
That seems a little … torturous, with all that casting and conditional stuff (as an aside, per-row functions rarely scale well in big tables).
Why don’t you just modify the
whereclause to stop the decrment if it’s already zero?If there are other columns you want updated irrespective of the value of
received, you can do that with a transaction:This will decrement
received, but not below zero, and it will changexyzzyno matter what. And it still keeps away from the per-row stuff that brings down many queries.