MYSQL:最简单的方法是只更新非空的字段?

cod*_*ama 2 mysql sql sql-update

假设我有这张表:

ID | col1 | col2 | col3 | col4
1  |  val |      |  val |
Run Code Online (Sandbox Code Playgroud)

有没有办法修改此查询:

UPDATE table set col1 = "bla", col2 = "bla", col3 = "bla", col4 = "bla where id = 1
Run Code Online (Sandbox Code Playgroud)

所以我最终得到:

ID | col1 | col2 | col3 | col4
1  |  val |  bla |  val |  bla
Run Code Online (Sandbox Code Playgroud)

换句话说,查询必须只更新非空字段.你是怎样做的?

Joh*_*Woo 8

最简单的答案是使用 COALESCE

UPDATE table 
set     col1 = COALESCE(col1,"bla"), 
        col2 = COALESCE(col2,"bla"), 
        col3 = COALESCE(col3,"bla"), 
        col4 = COALESCE(col4,"bla")
where   id = 1
Run Code Online (Sandbox Code Playgroud)

其他链接.

  • 不,coalesce只适用于空值,如果你有emty列试试这个,`UPDATE table set col1 = CASE WHEN col1 IS NULL或CHAR_LENGTH(TRIM(col1))= 0那么'bla'ELSE col1 END,...` (3认同)