[英]Sql query optimisation for million records
我有2個實體“ Customers
和Agreements
。
每個客戶可能有0 .. *個協議,這些協議可能處於active=1
或closed=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列上沒有索引,請執行第一項,否則查詢將需要時間
我認為您想要的exists
與not 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.