在本教程中,您将学习如何使用oracle not exists
运算符从一个数据中减去另一组数据集。
not exists
运算符与exists运算符相反。我们经常在子查询中使用not exists
运算符来从一个数据中减去另一组数据。
看一下使用not exists
运算符的以下语句:
select
*
from
table_name
where
not exists (subquery);
如果子查询不返回任何行,则not exists
运算符返回true
。 否则,它返回false
。
请注意,如果子查询返回任何具有
null
值的行,则not exists
运算符将返回false
。
请参阅示例数据库中的以下客户(customers
)和订单(orders
)表:
以下语句查找所有没有订单的客户:
select
name
from
customers
where
not exists (
select
null
from
orders
where
orders.customer_id = customers.customer_id
)
order by
name;
执行上面查询语句,得到以下结果 -
要查询归档没有订单的客户,请使用以下语句:
create table customers_archive as
select *
from
customers
where
not exists (
select
null
from
orders
where
orders.customer_id = customers.customer_id
);
执行上面查询语句后,再查询customers_archive
表中的数据,得到以下结果 -
要更新2017
年没有订单的客户的信用额度,请使用以下update语句:
update
customers
set
credit_limit = 0
where
not exists(
select
null
from
orders
where
orders.customer_id = customers.customer_id
and extract(year from order_date)='2017'
);
要从customers
表中删除2016
年和2017
年没有订单的所有客户,请使用以下delete语句:
delete
from
customers
where
not exists(
select
null
from
orders
where
orders.customer_id = customers.customer_id
and extract(year from order_date
) in(
2016,
2017
)
);
以下语句对子查询使用in运算符:
select
*
from
table_name
where
id in(subquery);
假设子查询返回四个值:1
,2
,3
和null
。可以重写上面的整个查询,如下所示:
select
*
from
table_name
where
id = 1
or id = 2
or id = 3
or id = null;
下面的表达式总是返回一个null
值,因为null
值不能和任何东西比较。
id = null
因此,如果子查询的结果集中的任何行为null
,则以下表达式将返回null
值。
id not in (subquery)
相比之下,null
不会影响not exist
运算符的结果,因为not exists
运算符仅检查子查询中是否存在行:
select
*
from
table_name
where
not exists(subquery);
总而言之,当存在null
值时,not exists
和not in
的行为会有所不同。
在本教程中,您已学习如何使用oracle not exists
运算符从一个数据中减去另一组数据。