在 MySQL 查詢中即使沒有結果也要返回一個值?


你可以使用 MySQL 中的 IFNULL() 函式來返回一個值,即使沒有結果。讓我們建立一個表。建立表的查詢。

mysql> create table IfNullDemo
   −> (
   −> Id int,
   −> Name varchar(100)
   −> );
Query OK, 0 rows affected (0.60 sec)

使用 insert 命令向表中插入一些記錄。查詢如下:

mysql> insert into IfNullDemo values(1,'John');
Query OK, 1 row affected (0.18 sec)

mysql> insert into IfNullDemo values(200,'Sam');
Query OK, 1 row affected (0.21 sec)

mysql> insert into IfNullDemo values(204,'Carol');
Query OK, 1 row affected (0.14 sec)

mysql> insert into IfNullDemo values(510,'Johnson');
Query OK, 1 row affected (0.18 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下:

mysql> select *from IfNullDemo;

以下是輸出:

+------+---------+
| Id   | Name    |
+------+---------+
|   1 | John     |
| 200 | Sam      |
| 204 | Carol    |
| 510 | Johnson  |
+------+---------+
4 rows in set (0.00 sec)

讓我們首先為 TRUE 條件返回一個值:

查詢如下:

mysql> select ifnull((select Id from IfNullDemo where Id = 200),'No Result Found') As ResultFound;

以下是輸出:

+-------------+
| ResultFound |
+-------------+
| 200         |
+-------------+
1 row in set (0.00 sec)

現在,讓我們使用 IFNULL 方法在沒有結果的情況下返回一個值。查詢如下:

mysql> select ifnull((select Id from IfNullDemo where Id = 400),'No Result Found') As ResultFound;

以下是輸出:

+-----------------+
| ResultFound     |
+-----------------+
| No Result Found |
+-----------------+
1 row in set (0.00 sec)

更新於:2019 年 7 月 30 日

8000+ 瀏覽量

開啟你的職業生涯

透過完成該課程獲得認證

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