在 MySQL 中根据空值在新列中显示自定义文本?
mysqlmysqli database更新于 2023/12/30 19:23:00
首先我们创建一个表 −
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)
以下是根据空值在新列中显示自定义文本的查询 −
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)