在 MySQL 中顯示 NULL 和 NOT NULL 記錄,但排除某個具體的值


要顯示 NULL 記錄,在 MySQL 中使用 IS NULL。要忽略單個值,請使用 != 運算子,它別名是 <> 運算子。

我們首先建立一個表 -

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   PlayerName varchar(40)
);
Query OK, 0 rows affected (0.50 sec)

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

mysql> insert into DemoTable(PlayerName) values('Adam');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(PlayerName) values(NULL);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(PlayerName) values('Sam');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(PlayerName) values('Mike');
Query OK, 1 row affected (0.08 sec)

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

mysql> select *from DemoTable;

這將生成以下輸出 -

+----+------------+
| Id | PlayerName |
+----+------------+
|  1 | Adam       |
|  2 | NULL       |
|  3 | Sam        |
|  4 | Mike       |
+----+------------+
4 rows in set (0.00 sec)

以下是顯示 NULL 和 NOT NULL 記錄的查詢,忽略單個特定記錄 -

mysql> select *from DemoTable
   where PlayerName!='Sam'
   or PlayerName IS NULL;

這將生成以下輸出 -

+----+------------+
| Id | PlayerName |
+----+------------+
|  1 | Adam       |
|  2 | NULL       |
|  4 | Mike       |
+----+------------+
3 rows in set (0.00 sec)

更新時間: 07-Oct-2019

147 次瀏覽

開啟您的職業生涯

透過完成課程獲取認證

開始
廣告