我正在使用以下查询来检索一组订单:
select count(distinct po.orderid)
from PostOrders po,
ProcessedOrders pro
where pro.state IN ('PENDING','COMPLETED')
and po.comp_code in (3,4)
and pro.orderid = po.orderid
查询返回结果4323,并且速度足够快。
但是我必须设置另一个条件,只有当它不存在于另一个表DiscarderOrders中时才会返回,我为查询添加了一个额外的条件:
select count(distinct po.orderid)
from PostOrders po,
ProcessedOrders pro
where pro.state IN ('PENDING','COMPLETED')
and po.comp_code in (3,4)
and pro.orderid = po.orderid
and po.orderid not in (select do.order_id from DiscardedOrders do)
上述查询需要花费大量时间才能继续运行。我可以对查询做些什么,以便快速执行?或者我是否需要先执行第一个查询,然后通过拍摄另一个查询来根据条件进行过滤?
答案 0 :(得分:3)
您可以尝试替换:
and po.orderid not in (select do.order_id from DiscardedOrders do)
通过
and not exists (select 1 from DiscardedOrders do where do.order_id = po.orderid)
答案 1 :(得分:2)
尝试使用JOIN
而不是NOT IN
SELECT COUNT(DISTINCT po.orderid) TotalCount
FROM PostOrders po
INNER JOIN ProcessedOrders pro
ON po.orderid = pro.orderid
LEFT JOIN DiscardedOrders do
ON po.orderid = do.orderid
WHERE po.comp_code IN (3,4) AND
pro.state IN ('PENDING','COMPLETED') AND
do.orderid IS NULL
或NOT EXISTS
SELECT COUNT(DISTINCT po.orderid) TotalCount
FROM PostOrders po
INNER JOIN ProcessedOrders pro
ON po.orderid = pro.orderid
WHERE po.comp_code IN (3,4) AND
pro.state IN ('PENDING','COMPLETED') AND
NOT EXISTS
(
SELECT 1
FROM DiscardedOrders do
WHERE po.orderid = do.orderid
)
答案 2 :(得分:0)
与distinct相同:
SELECT count(po.orderid)
FROM PostOrders po
WHERE po.comp_code IN (3,4)
AND EXISTS
(
SELECT 1 FROM ProcessedOrders pro
WHERE pro.orderid = po.orderid
AND pro.state IN ('PENDING','COMPLETED')
)
....
/