views:

155

answers:

5

I am trying to do this in mysql:

UPDATE table SET value = value - 1 WHERE blah blah

If value is 0 and this is run value is set to 4294967295. This is because it is an unsigned integer so it is looping round back to the maximum value.

How would I go about making it stay on zero instead? Can I do this purely in the sql?

+5  A: 
`AND value > 0`
Rob
*facepalm* Obviously. Thank you!
Mr_Chimp
A: 

You can run a second query or if-statement, checking whether it is set to the maximum and set it back to 0. But this is some kind of stupid...

Write a quick function which checks the entry, if it is already 0 do not perform any update query.

(if value >= 0, do not perform xy)

daemonfire300
+1  A: 
SET value = IF(value=0,0,value-1)
Joey
Smart, but Rob's is simpler
David Caunt
Yes, that's why he got my upvote too. But it's not the only possible solution :-)
Joey
I'll use rob's as it's simpler, but it's interesting that you can do this.
Mr_Chimp
or if(value,value-1,0)
ysth
+1  A: 

Use the where clause to say value > 0

Sunday night SQL always hurts me too. :-)

Karl
+1  A: 

Just append to the SQL string AND value > 0

Jacob Relkin