在 MySQL 中基于 null 值在新的列中显示自定义文本?
我们先创建一个表 -
mysql> create table DemoTable1953 ( StudentName varchar(20) ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable1953 values('Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1953 values(NULL); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1953 values('David'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1953 values(NULL); Query OK, 1 row affected (0.00 sec)
使用 select 语句从表中显示所有记录 -
mysql> select * from DemoTable1953;
这将生成以下输出 -
+-------------+ | StudentName | +-------------+ | Chris | | NULL | | David | | NULL | +-------------+ 4 rows in set (0.00 sec)
以下是根据 null 值在新的列中显示自定义文本的查询 -
mysql> select StudentName,IF(StudentName IS NULL,'Student Name Is Not Found','Student Name Found') as Name from DemoTable1953;
这将生成以下输出 -
+-------------+---------------------------+ | StudentName | Name | +-------------+---------------------------+ | Chris | Student Name Found | | NULL | Student Name Is Not Found | | David | Student Name Found | | NULL | Student Name Is Not Found | +-------------+---------------------------+ 4 rows in set (0.00 sec)
广告