views:

83

answers:

4

Quick newbie MySQL question. What would be the simplest way to ensure that the minimum value of a given field is 0?

Basically, we have a script that runs automatically and subtracts an integer value from the value of a field every 15 minutes--but we want any entry that gets to 0 to stay at 0 and not go negative.

This could be simply done with a loop in PHP but I'm trying to limit calls to the database...

Is there a simple way to either make the minimum value for a field 0 or make it so any negative value put in that field automatically becomes 0?

Thanks!

+2  A: 

you can set UNSIGNED attribute for your field. mysql will generate an error if you try to set this field to something < 0.

kgb
Nope. No error, just a warning. MySQL will still happilly do the subtraction. on a basic unsigned int field, `0 - 1 = 4294967295`
Marc B
yes, just a warning, but the row is inserted with 0 instead of the negative value. just tested it on mysql 5.1.41-3ubuntu12.6, int(10) unsigned NOT NULL column
kgb
+1  A: 

Have you tried a simple conditional "WHERE" or is the problem more complex than that?

UPDATE mytable SET mycolumn=mycolumn-1 WHERE mycolumn>0
treeface
+1  A: 

You could add the logic to your script to not subtract from the value if the value is already zero...

An update trigger that corrects negative values, setting them to zero is another idea.

OMG Ponies
A: 

Common way to do this would be CHECK constraint but MySQL does not support that.

So either make the column unsigned and/or make sure that in your application logic you are subtracting the value only when it is > 0.

Juha Syrjälä