mysql update increment int field that is null

折月煮酒 提交于 2019-11-29 01:22:49
UPDATE TableName SET column = IFNULL(column, 0) + 1 WHERE ...

More info on IFNULL. It returns the first argument if it is not NULL, the second otherwise.

Try setting the field as NOT NULL to get away with the problem so that default value of 0 is used instead of null. The other option is to set column as zero whenever it is null.

UPDATE TableName SET FieldName = '0' WHERE FieldName IS NULL

Other alternative would be to issue IFNULL to return 0 in case the column is null and then incrementing the column.

UPDATE TableName SET FieldName = IFNULL(FieldName,0) 

The SQL standard would be to use COALESCE(); this has been available in MySQL since version 3.23 (which was released into production in 2001):

UPDATE mytable
   SET mycolumn = COALESCE(mycolumn, 0) + 1
 WHERE my_other_columns = ...

I can't see any reason to choose IFNULL() over COALESCE() here.

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!