MySQL 中是否存在一個運算子可以實現多個 NOT 條件,比如 WHERE id != 5 AND id != 10 AND id != 15?


是的,MySQL 帶有 NOT IN。

語法如下

SELECT *FROM yourTableName WHERE yourColumnName NOT IN(1,2,7);

為了理解如上語法,讓我們建立一個表。建立表的查詢如下

mysql> create table User_informations
   - > (
   - > UserId int,
   - > UserName varchar(20)
   - > );
Query OK, 0 rows affected (0.47 sec)

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

查詢如下

mysql> insert into User_informations values(12,'Maxwell');
Query OK, 1 row affected (0.17 sec)
mysql> insert into User_informations values(7,'David');
Query OK, 1 row affected (0.10 sec)
mysql> insert into User_informations values(1,'Ramit');
Query OK, 1 row affected (0.36 sec)
mysql> insert into User_informations values(10,'Bob');
Query OK, 1 row affected (0.19 sec)
mysql> insert into User_informations values(2,'Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into User_informations values(14,'Sam');
Query OK, 1 row affected (0.23 sec)
mysql> insert into User_informations values(6,'Mike');
Query OK, 1 row affected (0.12 sec)
mysql> insert into User_informations values(4,'Robert');
Query OK, 1 row affected (0.13 sec)

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

查詢如下

mysql> select *from User_informations;

以下是輸出

+--------+----------+
| UserId | UserName |
+--------+----------+
|     12 | Maxwell  |
|      7 | David    |
|      1 | Ramit    |
|     10 | Bob      |
|      2 | Carol    |
|     14 | Sam      |
|      6 | Mike     |
|      4 | Robert   |
+--------+----------+
8 rows in set (0.00 sec)

以下是使用 NOT IN() 實現您需求的示例。

查詢如下

mysql> select *from User_informations where UserId NOT IN(1,2,7);

以下是輸出

+--------+----------+
| UserId | UserName |
+--------+----------+
|     12 | Maxwell  |
|     10 | Bob      |
|     14 | Sam      |
|      6 | Mike     |
|      4 | Robert   |
+--------+----------+
5 rows in set (0.00 sec)

更新於: 30-Jul-2019

447 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始吧
廣告
© . All rights reserved.