SQL查询优化百万条记录

时间:2019-07-08 16:57:37

标签: sql oracle

我有2个实体CustomersAgreements

每个客户可能有0 .. *个协议,可以是active=1closed=0

我正在尝试选择没有任何协议(表Agreements中没有记录)的客户,或者在一个查询中选择带有标志“ closed” = 0的客户。

协议表有几百万条记录。

任何建议如何最好地做到这一点?

2 个答案:

答案 0 :(得分:0)

使用相关子查询,我请您使用一个关系列customerid

select c* from customer c
where  exists( select 1 from Aggrements a where c.customerid=a.customerid
                                          and a.closed=0)
or (not exists ( select 1 from Aggrements a where c.customerid=a.customerid
                                          and a.active=1)
   )

如果您在customerid列上没有索引,请首先执行该操作,否则查询将需要时间

答案 1 :(得分:0)

我认为您想要existsnot exists,采用以下逻辑:

select c.*
from customers c
where not exists (select 1
                  from Agreements a
                  where a.customerid = c.customerid
                 ) or
     exists (select 1
             from Agreements a 
             where a.customerid = c.customerid and
                   a.closed = 0
            );

为了提高性能,您希望在agreements(customerid, closed)上建立索引。

相关问题