Oracle 专题
专题目录
您的位置:database > Oracle专题 > Oracle Not Exists运算符
Oracle Not Exists运算符
作者:--    发布时间:2019-11-20

在本教程中,您将学习如何使用oracle not exists运算符从一个数据中减去另一组数据集。

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

oracle not exists例子

请参阅示例数据库中的以下客户(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
            )
    );

oracle not exists与not in

以下语句对子查询使用in运算符:

select
 *
from
    table_name
where
    id in(subquery);

假设子查询返回四个值:1,2,3null。可以重写上面的整个查询,如下所示:

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 existsnot in的行为会有所不同。

在本教程中,您已学习如何使用oracle not exists运算符从一个数据中减去另一组数据。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册