在本教程中将学习如何使用oracle in
运算符来确定值是否与列表或子查询中的任何值相匹配。
oracle in
运算符确定值是否匹配列表或子查询中的任何值。
注:子查询是嵌套在另一个查询中的查询,可通过在子查询教程中了解子查询用法。
确定表达式是否与值列表匹配的oracle in
运算符的语法如下所示:
expression [not] in (v1,v2,...)
并且表达式的语法与子查询匹配:
expression [not] in (subquery)
参数
在上面语法中,这里将介绍每个参数含义:
in
运算符后面是逗号分隔值列表,用于测试匹配。所有值必须与表达式具有相同的数据类型。返回值
如果表达式(expression)的值等于值列表中的任何值或由子查询返回的结果集,则in
运算符返回true
。 否则,它返回false
。
not
运算符否定in
运算符的结果。
我们将使用示例数据库中的orders
和employees
表进行演示:
以下语句查找所有销售员id为54
,55
和56
所负责的订单:
select
order_id,customer_id,status,salesman_id
from
orders
where
salesman_id in (54,55,56)
order by
order_id;
执行上面查询语句,得到以下结果 -
如上图中所示,查询结果集返回了salesman_id
列中值为54
,55
或56
的所有订单。同样,以下示例将检索状态(status
)列的值为"pending"
或"canceled"
的销售订单信息:
select
order_id, customer_id, status, salesman_id
from
orders
where
status in('pending','canceled')
order by
order_id;
执行上面查询语句返回状态(status
)列的值为"pending"
或"canceled"
的销售订单信息,如下所示 -
这个示例演示如何查找状态(status
)不是"pending"
或"canceled"
的订单:
select
order_id, customer_id, status, salesman_id
from
orders
where
status not in( 'shipped', 'canceled')
order by
order_id;
执行上面查询语句返回状态(status
)列的值不是"pending"
或"canceled"
的销售订单信息,如下所示 -
以下示例返回负责订单状态为取消(canceled
)的销售员的id,名字和姓氏,参考以下查询语句 -
select employee_id, first_name, last_name
from employees
where
employee_id in(
select
distinct salesman_id
from
orders
where
status = 'canceled'
)
order by first_name;
执行上面查询语句,得到以下结果 -
在这个例子中,子查询首先执行并返回一个销售员id列表:
select
distinct salesman_id
from
orders
where
status = 'canceled'
执行上面查询语句,得到以下结果 -
这些销售人员id
用于外部查询,查找所有员工的id
与销售员id
列表中的任何id
相同。
请参阅以下customers
和orders
表的er图:
以下示例使用not in
来查找尚未下过任何订单的客户:
select
customer_id, name
from customers
where
customer_id not in(
select
customer_id
from
orders
);
执行上面查询语句,得到以下结果 -
以下示例显示如何获得销售员id为60
,61
和62
的销售订单:
select
customer_id, status, salesman_id
from
orders
where
salesman_id in(60, 61, 62)
order by
customer_id;
执行上面查询语句,得到以下结果 -
上面语句相当于:
select
customer_id,
status,
salesman_id
from
orders
where
salesman_id = 60
or salesman_id = 61
or salesman_id = 62
order by
customer_id;
请注意,表达式:
salesman_id not in (60,61,62);
与以下语句具有相同的效果:
salesman_id = 60
and salesman_id = 61
and salesman_id = 62;
在本教程中,您已学习如何使用oracle in
运算符来查询与值列表或子查询匹配的数据。
select customer_id status salesman_idfrom orderswhere salesman_id in60 61 62order by customer_id语句运行结果与图片所示不同 提交时间:2019-08-30