其中一個列值為 MySQL 中的空值時,連線兩列


若要避免在執行查詢時出現問題,請使用 IFNULL()。我們首先建立一個表 -

mysql> create table DemoTable1793
     (
     StudentFirstName varchar(20),
     StudentLastName varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)

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

mysql> insert into DemoTable1793 values('John','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1793 values('Carol',NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1793 values(NULL,'Brown');
Query OK, 1 row affected (0.00 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select * from DemoTable1793;

這將產生以下輸出 -

+------------------+-----------------+
| StudentFirstName | StudentLastName |
+------------------+-----------------+
| John             |           Smith |
| Carol            |            NULL |
| NULL             |           Brown |
+------------------+-----------------+
3 rows in set (0.00 sec)

以下是其中一個列值為 null 時連線兩列的查詢 -

mysql> select concat(ifnull(StudentFirstName,''),ifnull(StudentLastName,'')) from DemoTable1793;

這將產生以下輸出 -

+----------------------------------------------------------------+
| concat(ifnull(StudentFirstName,''),ifnull(StudentLastName,'')) |
+----------------------------------------------------------------+
| JohnSmith                                                      |
| Carol                                                          |
| Brown                                                          |
+----------------------------------------------------------------+
3 rows in set (0.00 sec)

更新於:2019 年 12 月 23 日

1000+ 瀏覽量

開啟你的 職業

完成課程後獲得認證

開始
廣告
© . All rights reserved.