簡體   English   中英

SQL查詢優化百萬條記錄

[英]Sql query optimisation for million records

我有2個實體“ CustomersAgreements

每個客戶可能有0 .. *個協議,這些協議可能處於active=1closed=0

我正在嘗試選擇沒有任何協議(表Agreements沒有記錄)的客戶端,或在一個查詢中具有標志為“ closed” = 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列上沒有索引,請執行第一項,否則查詢將需要時間

我認為您想要的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)的索引agreements(customerid, closed)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM