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_commentsis defined asUNSIGNEDand if its value is0then the evaluation of the expressiontotal_comments - 1throws an error.A workaround would be to compare
total_commentsto 1 insideGREATEST()and after that do the subtraction: