在 MySQL 中,如果列 A 为空,则更新;如果非空,则更新列 B;如果两个列都不为空,则不操作
为此,请使用具有 IS NULL 属性的 IF()。让我们先创建一个表 −
mysql> create table DemoTable1976 ( FirstName varchar(20), LastName varchar(20) ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令向表中插入一些记录 −
mysql> insert into DemoTable1976 values('John','Doe'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1976 values('John',NULL); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1976 values(NULL,'Miller'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1976 values('Chris','Brown'); Query OK, 1 row affected (0.00 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1976;
这将生成以下输出 −
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | John | Doe | | John | NULL | | NULL | Miller | | Chris | Brown | +-----------+----------+ 4 rows in set (0.00 sec)
以下是如果列为空则更新列,否则更新另一列,如果两个列都不为空则不执行操作的查询 −
mysql> update DemoTable1976 set FirstName=if(FirstName IS NULL,'David',FirstName), LastName=if(LastName IS NULL,'Brown',LastName); Query OK, 2 rows affected (0.00 sec) Rows matched: 4 Changed: 2 Warnings: 0
让我们再次检查表记录 −
mysql> select * from DemoTable1976;
这将生成以下输出 −
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | John | Doe | | John | Brown | | David | Miller | | Chris | Brown | +-----------+----------+ 4 rows in set (0.00 sec)
广告