技术文章和资源

技术文章(时间排序)

热门类别

Python PHP MySQL JDBC Linux

MySQL 中是否有运算符来实现多个 NOT 条件,如 WHERE id != 5 AND id != 10 AND id != 15?

mysqlmysqli database

是的,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)

相关文章