MYSQL:只更新非空字段的最充分方式?
假设我有这张桌子:MYSQL:只更新非空字段的最充分方式?,mysql,sql,sql-update,Mysql,Sql,Sql Update,假设我有这张桌子: ID | col1 | col2 | col3 | col4 1 | val | | val | 有没有办法修改此查询: UPDATE table set col1 = "bla", col2 = "bla", col3 = "bla", col4 = "bla where id = 1 因此,我最终得出以下结论: ID | col1 | col2 | col3 | col4 1 | val | bla | val | bla 换句话说,查询必
ID | col1 | col2 | col3 | col4
1 | val | | val |
有没有办法修改此查询:
UPDATE table set col1 = "bla", col2 = "bla", col3 = "bla", col4 = "bla where id = 1
因此,我最终得出以下结论:
ID | col1 | col2 | col3 | col4
1 | val | bla | val | bla
换句话说,查询必须只更新不为null的字段。如何做到这一点?最简单的答案是使用
合并
UPDATE table
set col1 = COALESCE(col1,"bla"),
col2 = COALESCE(col2,"bla"),
col3 = COALESCE(col3,"bla"),
col4 = COALESCE(col4,"bla")
where id = 1
其他链接
您也可以使用IsNUll代替Coalesce,Coalesce和IsNUll在许多方面是等效的
Update Table
set col1 = Isnull(col1,'bla'),...
当然,如果RD希望它也适用于空字符串,JW已经给出了一个解决方案即使值必须为“”(空)且不一定为空,这仍然有效吗?不,coalesce仅适用于空值,如果您有emty列,请尝试此方法,更新表集col1=CASE,当col1为空或字符长度(TRIM(col1))时=0然后“bla”ELSE col1 END,…
是否愿意夸大这一点为何被否决?