0

我的以下查询有点慢,您可以看到 where 子句中有几个嵌套查询,有人能提出更好的解决方案吗?

SELECT m.briefmedialist, 
       Count(DISTINCT s.value) AS selected, 
       m.briefmedialistid 
FROM   vwmedialistmediachannels m 
       LEFT JOIN sessionfilters s 
              ON s.field = 'Media' 
                 AND m.briefmedialistid = s.value 
                 AND s.sessionid = @SessionID 
WHERE  m.id = (SELECT d.briefid 
               FROM   dashboards d 
               WHERE  d.dashboardguid IN (SELECT value 
                                          FROM   sessionfilters s 
                                          WHERE  s.sessionid = @SessionID 
                                                 AND s.field = 'DashboardID')) 
GROUP  BY m.briefmedialist, 
          m.briefmedialistid 
ORDER  BY m.briefmedialist 
4

2 回答 2

0

您可以使用 JOIN 轻松替换子查询:

SELECT m.briefmedialist, 
       Count(DISTINCT s.value) AS selected, 
       m.briefmedialistid 
FROM   vwmedialistmediachannels m
    INNER JOIN dashboards d ON d.briefid = m.id
    INNER JOIN sessionfilters sd ON sd.VALUE = d.dashboardguid
    LEFT JOIN sessionfilters s  ON s.field = 'Media' 
                AND m.briefmedialistid = s.value 
                AND s.sessionid = @SessionID 
WHERE sd.sessionid = @SessionID 
   AND sd.field = 'DashboardID'
GROUP  BY m.briefmedialist, 
          m.briefmedialistid 
ORDER  BY m.briefmedialist 

不确定这是否会对您的性能有很大帮助,因为还有许多我们看不到的其他因素——比如索引、表结构、列类型。另外,我想,那vwmedialistmediachannels是一种观点——所以它背后的任何东西都可能是减慢查询速度的原因。

于 2013-07-18T12:28:07.550 回答
0
SELECT m.briefmedialist, 
       Count(DISTINCT d.dashboardguid) AS selected, 
       m.briefmedialistid 
  FROM vwmedialistmediachannels m 
  LEFT JOIN sessionfilters s 
    ON s.value = m.briefmedialistid 
   AND s.field = 'Media'
   AND s.sessionid = @SessionID
  JOIN dashboards d
    ON d.briefid = m.id 
  JOIN sessionfilters sf
    ON sf.Value = d.dashboardguid 
   AND sf.field = 'DashboardID'
   AND sf.sessionid = @SessionID
GROUP BY m.briefmedialist, 
         m.briefmedialistid 
ORDER BY m.briefmedialist

与 Nenad 类似,但将条件拉入连接有时可以让查询优化器提前过滤

在查询优化器中检查它。
在连接条件上有索引。
最后的手段是尝试加入提示(合并、散列、循环)。
在复杂查询中,查询优化器不会评估连接选项,但我认为这里不会出现这种情况。
如果您看到所有循环连接,请尝试合并两个 sessionfilters 连接。

下一步是创建带有声明 PK 的 #temp 表

select distinct(s.value)
  from sessionfilters s 
 where s.field = 'Media'
   AND s.sessionid = @SessionID 

select distinct(sf.value)
  from sessionfilters sf
 where sf.sessionid = @SessionID 
   AND sf.field = 'DashboardID'
于 2013-07-18T13:18:43.903 回答