如果列为空,返回特定字符串的 MySQL 查询?
让我们先创建一个表 -
mysql> create table DemoTable -> ( -> Name varchar(100) -> ); Query OK, 0 rows affected (0.85 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('David'); Query OK, 1 row affected (0.17 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
输出
+-------+ | Name | +-------+ | John | | NULL | | NULL | | David | +-------+ 4 rows in set (0.00 sec)
以下是如果列为空则返回特定字符串的查询 -
mysql> SELECT COALESCE(Name, 'Not Valid') from DemoTable;
输出
+-----------------------------+ | COALESCE(Name, 'Not Valid') | +-----------------------------+ | John | | Not Valid | | Not Valid | | David | +-----------------------------+ 4 rows in set (0.00 sec)
广告