如何跳過 MySQL 中的空值和 null 值?


若要在 MySQL 中跳過空值和 null 值,請使用以下語法

select *from yourTableName where yourColumnName IS NOT NULL AND yourColumnName <> '';

我們首先建立一個表

mysql> create table DemoTable (Id int, FirstName varchar(20));
Query OK, 0 rows affected (0.66 sec)

以下是使用 insert 命令在表中插入記錄的查詢

mysql> insert into DemoTable values(100,'Larry');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(101,'');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(102,'Chris');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(103,null);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(104,' ');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(105,'Robert');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(106,null);
Query OK, 1 row affected (0.13 sec)

以下是使用 select 命令從表中顯示記錄的查詢

mysql> select *from DemoTable;

這將生成以下帶有空值和 NULL 的輸出

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 100  | Larry     |
| 101  |           |
| 102  | Chris     |
| 103  | NULL      |
| 104  |           |
| 105  | Robert    |
| 106  | NULL      |
+------+-----------+
7 rows in set (0.00 sec)

以下是跳過空值以及 MySQL 中 null 的查詢

mysql> select *from DemoTable where FirstName IS NOT NULL AND FirstName <> '';

這將生成以下輸出

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 100  | Larry     |
| 102  | Chris     |
| 105  | Robert    |
+------+-----------+
3 rows in set (0.03 sec)

更新日期: 2019 年 7 月 30 日

超過 4K 次檢視

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告