sql - SQL Server - Exists 的替代方案(子查询太多)
问题描述
我正在寻找一种方法来提高具有太多现有链接子查询的查询的性能。
我的问题是我有一个 Orders Detail 表,对于订单的每个项目,都有一个特定的类别(存储在另一个表中,但现在无关紧要)。
我必须根据该类别的不同组合来检测特定的“组”订单: - A 组:带有 13 + 15 类商品的订单 + 任何(66、67、68、69)商品的订单 带有 77 类商品的订单 + 78 + (66, 67, 68, 69, 71, 71) 中的任何一个
到目前为止,我所做的是使用链接存在的巨大查询来查找满足该条件的订单,但这是一场性能噩梦。
我希望有更好的方法来做到这一点,因为我的表有数百万条记录......
非常感谢!!!
解决方案
我会使用group by
和having
:
select order_id
from order_details od
group by order_id
having sum(case when category = 13 then 1 else 0 end) > 0 and -- at least one 13
sum(case when category = 15 then 1 else 0 end) > 0 and -- at least one 15
sum(case when category in (66, 67, 68, 69) then 1 else 0 end) > 0 -- at least one of these
这可以很容易地扩展。所以对于第二组:
having (sum(case when category = 13 then 1 else 0 end) > 0 and -- at least one 13
sum(case when category = 15 then 1 else 0 end) > 0 and -- at least one 15
sum(case when category in (66, 67, 68, 69) then 1 else 0 end) > 0
) or
(sum(case when category = 77 then 1 else 0 end) > 0 and -- at least one 13
sum(case when category = 78 then 1 else 0 end) > 0 and -- at least one 15
sum(case when category in (66, 67, 68, 69, 71, 71) then 1 else 0 end) > 0
)
推荐阅读
- java - 我应该添加什么才能打印代码而不是地址?
- python - 检查位置的坐标是否在边界内
- ios - 使用 NetworkExtension 阻止 URL
- microsoft-graph-api - 尝试获取 singleValueExtendedProperties 时收到 400 和 500
- intellij-idea - Intellij IDEA 控制台中的运行时
- typescript - Typescript:这种用于键入函数的键入方法是什么?
- python - tkinter 框架没有几何图形 python tkinter
- django - Django QuerySets - 相关模型
- git - git合并重复提交
- c++ - 如何使用 c++ 中的构造函数初始化 unique_ptrs 的 2d 向量?