在本教程中,您将学习如何使用sql in
运算符将列中的值与一组值进行比较。
in
运算符是一个逻辑运算符,用于将值与一组值进行比较。 如果值在值集内,则in
运算符返回true
。 否则,它返回false
或unknown
。
以下是in
运算符的语法:
expression in (value1,value2,...)
in
运算符通常用于select,update或delete语句的where
子句中。 它也广泛用于子查询中。
使用in
运算符的条件可以使用一个或多个or
运算符重写,如下所示:
expression = value1 or expression = value2 or ...
要否定in
运算符的结果,请使用not
运算符:
expression not in (value1, value2,...)
如果表达式与列表中的任何值都不匹配,则not in
运算符返回true
,否则返回false
。
同样,可以使用and
运算符重写not in
运算符,如下所示:
expression != value1 and expression != value2 and...
请注意,如果列表中的任何值(value1
,value2
,...
)为null
,则in
运算符不返回任何行。
我们将使用示例数据库中的employees
表来演示in
运算符的功能。
mysql> desc employees;
+---------------+--------------+------+-----+---------+----------------+
| field | type | null | key | default | extra |
+---------------+--------------+------+-----+---------+----------------+
| employee_id | int(11) | no | pri | null | auto_increment |
| first_name | varchar(20) | yes | | null | |
| last_name | varchar(25) | no | | null | |
| email | varchar(100) | no | | null | |
| phone_number | varchar(20) | yes | | null | |
| hire_date | date | no | | null | |
| job_id | int(11) | no | mul | null | |
| salary | decimal(8,2) | no | | null | |
| manager_id | int(11) | yes | mul | null | |
| department_id | int(11) | yes | mul | null | |
+---------------+--------------+------+-----+---------+----------------+
10 rows in set
要查找工作id为8
,9
或10
的所有员工,请使用in
运算符,如下所示:
select
employee_id, first_name, last_name, job_id
from
employees
where
job_id in (8, 9, 10)
order by
job_id;
执行上面示例代码,得到以下结果 -
要查找工作id不是8
,9
或10
的所有员工,请使用not in
运算符,如下所示:
select
employee_id, first_name, last_name, job_id
from
employees
where
job_id not in (8, 9, 10)
order by
job_id;
sql in带有子查询示例
子查询是嵌套在另一个查询中的查询。 以下查询查找市场营销 和it部门的部门id:
select
department_id
from
departments
where
department_name = '市场营销'
or department_name = 'it';
执行上面示例代码,得到以下结果 -
+---------------+
| department_id |
+---------------+
| 2 |
| 6 |
+---------------+
2 rows in set
该查询返回两个部门的列表。 可以将此列表提供给in
运算符,以查找在市场营销 和it部门工作的所有员工。
select
employee_id, first_name, last_name, salary
from
employees
where
department_id in (2, 6);
执行上面查询语句,得到以下结果 -
要使它更简单,可以使用在第二个查询中嵌套第一个查询的子查询来实现:
select
employee_id, first_name, last_name, salary
from
employees
where
department_id in (select
department_id
from
departments
where
department_name = '市场营销'
or department_name = 'it')
在本教程中,您已经学习了如何使用sql in
运算符来测试值是否在值列表或子查询中的条件。