0

更新:更改标题。上一个标题“UNION 代替 OR 总是可以加快查询速度吗?”

这是我的查询。问题是关于 OR 的倒数第二行:

SELECT distinct bigUnionQuery.customer
FROM ((SELECT buyer.customer
       FROM membership_vw buyer
       JOIN account_vw account
       ON account.buyer = buyer.id
       WHERE account.closedate >= 'some_date')
       UNION
       (SELECT joint.customer
       FROM entity_vw joint
       JOIN transactorassociation_vw assoc
       ON assoc.associatedentity = joint.id
       JOIN account_vw account
       ON account.buyer = assoc.entity
       WHERE assoc.account is null and account.closedate >= 'some_date')
       UNION
       (SELECT joint.customer
       FROM entity_vw joint
       JOIN transactorassociation_vw assoc
       ON assoc.associatedentity = joint.id
       JOIN account_vw account
       ON account.id = assoc.account
       WHERE account.closedate >= '2021-02-11 00:30:22.339')) 
AS bigUnionQuery
JOIN entity_vw
ON entity_vw.customer = bigUnionQuery.customer OR entity_vw.id = bigUnionQuery.customer
WHERE entity_vw.lastmodifieddate >= 'some_date';

原始查询在倒数第二行中没有 OR。在此处添加 OR 会减慢查询速度。我想知道是否有办法在这里使用 UNION 来加速它。

我试着做(伪):

bigUnionQuery bq join entity_vw e on e.customer = bq.customer
union
bigUnionQuery bq join entity_vw e on e.id = bq.customer

但这进一步减慢了查询速度,可能是因为 bigUnionQuery 是一个大而慢的查询,并且在 UNION 中运行两次并不是正确的方法。在这里使用 UNION 的正确方法是什么,或者使用 OR 总是会更快?

4

1 回答 1

1

Does UNION instead of OR always speed up queries? In some cases it does. I think it depends on your indexes too. I have worked on tables with 1 million records and my queries' speed usually improves if I use union instead of 'or' or 'and'.

于 2021-02-13T16:23:34.543 回答