MySQL CASE 语句将自定义值替换到 NULL
让我们首先创建一个表 −
mysql> create table DemoTable ( FirstName varchar(20) ); Query OK, 0 rows affected (1.15 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Adam'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.09 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这会产生以下输出 −
+-----------+ | FirstName | +-----------+ | John | | NULL | | Adam | | NULL | +-----------+ 4 rows in set (0.00 sec)
现在让我们使用 CASE 语句 −
mysql> select case when FirstName is NULL then 'UNKNOWN NAME' else FirstName end AS FirstName from DemoTable;
这会产生以下输出 −
+--------------+ | FirstName | +--------------+ | John | | UNKNOWN NAME | | Adam | | UNKNOWN NAME | +--------------+ 4 rows in set (0.00 sec)
我们还可以使用 IFNULL() 获得相同的结果 −
mysql> select IFNULL(FirstName,'UNKNOWN NAME') AS FirstName from DemoTable;
这会产生以下输出 −
+--------------+ | FirstName | +--------------+ | John | | UNKNOWN NAME | | Adam | | UNKNOWN NAME | +--------------+ 4 rows in set (0.00 sec)
广告