在 MySQL 中基於 null 值在新的列中顯示自定義文字?


我們先建立一個表 -

mysql> create table DemoTable1953
   (
   StudentName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

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

mysql> insert into DemoTable1953 values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1953 values(NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1953 values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1953 values(NULL);
Query OK, 1 row affected (0.00 sec)

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

mysql> select * from DemoTable1953;

這將生成以下輸出 -

+-------------+
| StudentName |
+-------------+
| Chris       |
| NULL        |
| David       |
| NULL        |
+-------------+
4 rows in set (0.00 sec)

以下是根據 null 值在新的列中顯示自定義文字的查詢 -

mysql> select StudentName,IF(StudentName IS NULL,'Student Name Is Not Found','Student Name Found') as Name from DemoTable1953;

這將生成以下輸出 -

+-------------+---------------------------+
| StudentName | Name                      |
+-------------+---------------------------+
| Chris       | Student Name Found        |
| NULL        | Student Name Is Not Found |
| David       | Student Name Found        |
| NULL        | Student Name Is Not Found |
+-------------+---------------------------+
4 rows in set (0.00 sec)

更新於:31-12-2019

498 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告