1

我有一个包含多列 A、B 和 C 的 MySQL 表。

我想只使用一个 SQL 语句来更新这些列。但是,有时某些列可能为空。

因此,如果 A 为空,则仅更新 B 和 C。

如果 A 和 B 为空,则只更新 C。

依此类推,与所有其他组合。

我怎样才能在一个声明中做到这一点?

谢谢。

4

2 回答 2

7

您可以在更新子句中使用 if:

update test_update set A=if(A is null, null, 'A2'), B=if(B is null, null, 'B2'), C=if(C is null, null, 'C2');

示例运行:

MariaDB [test]> select * from test_update;
+------+------+------+
| A    | B    | C    |
+------+------+------+
| A1   | NULL | NULL |
| NULL | B1   | NULL |
| NULL | NULL | C1   |
| A1   | B1   | NULL |
| A1   | NULL | C1   |
| NULL | B1   | C1   |
| A1   | B1   | C1   |
+------+------+------+
7 rows in set (0.00 sec)

MariaDB [test]> update test_update set A=if(A is null, null, 'A2'), B=if(B is null, null, 'B2'), C=if(C is null, null, 'C2');
Query OK, 7 rows affected (0.00 sec)
Rows matched: 7  Changed: 7  Warnings: 0

MariaDB [test]> select * from test_update;
+------+------+------+
| A    | B    | C    |
+------+------+------+
| A2   | NULL | NULL |
| NULL | B2   | NULL |
| NULL | NULL | C2   |
| A2   | B2   | NULL |
| A2   | NULL | C2   |
| NULL | B2   | C2   |
| A2   | B2   | C2   |
+------+------+------+
7 rows in set (0.00 sec)
于 2015-10-02T23:25:09.407 回答
1

您只想更新非NULL值似乎很奇怪,但这就是您编写语句的方式。我会把它写成:

update test_update
    set A = (case when A is not null then 'A' end),
        B = (case when B is not null then 'B' end),
        C = (case when C is not null then 'C' end)
     where A is not null or B is not null or C is not null;

当然,常量字符串是您想要的任何新值。

于 2015-10-03T01:55:21.417 回答