如何在 MySQL 查詢中替換“空集”?


若要替換一條不存在的記錄,請在 MySQL 中使用 COALESCE。COALESCE 有助於替換 NULL 值。我們先建立一個表 −

mysql> create table DemoTable
   -> (
   -> Code varchar(20)
   -> );
Query OK, 0 rows affected (1.64 sec)

使用 insert 命令向表中插入一些記錄 −

mysql> insert into DemoTable values('10');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('45');
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values('78');
Query OK, 1 row affected (0.21 sec)

使用 select 語句從表中顯示所有記錄 −

mysql> select *from DemoTable;

這將產生以下輸出 −

+------+
| Code |
+------+
| 10   |
| 45   |
| 78   |
+------+
3 rows in set (0.00 sec)

以下是在 MySQL 查詢中替換“空集”的查詢 −

mysql> select COALESCE(MAX(Code), 'false') AS WhenReturnSetIsEmpty
   -> from DemoTable
   -> where Code='90';

這將產生以下輸出 −

+----------------------+
| WhenReturnSetIsEmpty |
+----------------------+
| false                |
+----------------------+
1 row in set (0.00 sec)

更新日期:13-Dec-2019

603 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.