MySQL: Convert Negative Value to Zero

在 MySQL 裡經常會變動一些關於計數的數值。例如

UPDATE table SET count = count + 1

碰到減一的情況時,為了避免計數變成負值,可以多加一個判斷。

UPDATE table SET count = GREATEST(count - 1, 0)

如果是碰到空值的話,再多一步。

UPDATE table SET count = GREATEST(IFNULL(count, 0) - 1, 0)

簡單。


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version