I have a trigger like this which keeps the total value in the parent table:
UPDATE posts p SET total_comments = GREATEST(total_comments - 1, 0) WHERE old.post_id = p.id
I've used GREATEST()
to avoid negative numbers, but still, I get this error if the current value of total_comments
is 0
and then the trigger executes:
#1690 - BIGINT UNSIGNED value is out of range in (mydb.p.total_comments - 1)
Any solution?
From Out-of-Range and Overflow Handling:
In your case
total_comments
is defined asUNSIGNED
and if its value is0
then the evaluation of the expressiontotal_comments - 1
throws an error.A workaround would be to compare
total_comments
to 1 insideGREATEST()
and after that do the subtraction: