如果行非 NULL,則從該行返回該值,否則使用 MySQL 返回另一列中的其他行值


為此,您可以使用 IFNULL()。我們首先建立一個表 -

mysql> create table DemoTable
(
   FirstName varchar(100),
   LastName varchar(100)
);
Query OK, 0 rows affected (0.62 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable values('John','Doe');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable values(NULL,'Taylor');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('David',NULL);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(NULL,'Miller');
Query OK, 1 row affected (0.12 sec)

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

mysql> select *from DemoTable;

這將產生以下輸出 -

+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| John      | Doe      |
| NULL      | Taylor   |
| David     | NULL     |
| NULL      | Miller   |
+-----------+----------+
4 rows in set (0.00 sec)

以下是返回行值(如果它不是 NULL,否則返回另一列中的另一個行值)的查詢 -

mysql> select ifnull(FirstName,LastName) as Result from DemoTable;

這將產生以下輸出 -

+--------+
| Result |
+--------+
| John   |
| Taylor |
| David  |
| Miller |
+--------+
4 rows in set (0.00 sec)

更新日期:30-Sep-2019

216 次觀看

開啟你的 事業

完成課程獲取認證

開始
廣告
© . All rights reserved.