mysql update increment int field that is null

戏子无情 提交于 2019-11-27 15:53:25

问题


I have a very large table with two INT columns that are null on Default. This is a problem because since they are INT fields, it would help in many cases if they were originally set to 0.

So my questions are, is there a way I can UPDATE and INCREMENT(+1) these fields while they are like this (null on Default)? BTW.. I didn't have luck so far, it seems increment only works when the default=0

..or is my only option to Change the Default to none from null


回答1:


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.




回答2:


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) 



回答3:


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.



来源:https://stackoverflow.com/questions/5367212/mysql-update-increment-int-field-that-is-null

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