首页 > 解决方案 > SQL Server - Exists 的替代方案(子查询太多)

问题描述

我正在寻找一种方法来提高具有太多现有链接子查询的查询的性能。

我的问题是我有一个 Orders Detail 表,对于订单的每个项目,都有一个特定的类别(存储在另一个表中,但现在无关紧要)。

我必须根据该类别的不同组合来检测特定的“组”订单: - A 组:带有 13 + 15 类商品的订单 + 任何(66、67、68、69)商品的订单 带有 77 类商品的订单 + 78 + (66, 67, 68, 69, 71, 71) 中的任何一个

到目前为止,我所做的是使用链接存在的巨大查询来查找满足该条件的订单,但这是一场性能噩梦。

我希望有更好的方法来做到这一点,因为我的表有数百万条记录......

非常感谢!!!

标签: sqlsql-serverexists

解决方案


我会使用group byhaving

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    
       ) 

推荐阅读