如何解决是否可以在这里使用 UNION 而不是 OR?
更新:更改了标题。 Previous title “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 总是会更快?
解决方法
UNION 而不是 OR 总是能加快查询速度吗?在某些情况下确实如此。我认为这也取决于您的索引。我处理过包含 100 万条记录的表,如果我使用 union 而不是“or”或“and”,我的查询速度通常会提高。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。