2013-07-18 67 views
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 
+0

您可以添加一個索引,使查詢執行得更快 – 2013-07-18 12:10:16

+0

你能告訴我們查詢中涉及的表的結構,他們擁有的索引以及該查詢試圖產生的是什麼? –

+0

你是否確定***子查詢是性能問題的來源? –

回答

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 

類似內納德但提拉條件爲加盟有時讓查詢優化器過濾器早

檢查它在查詢優化器。
有連接條件的索引。
最後的手段是嘗試加入提示(合併,哈希,循環)。
在複雜的查詢上查詢優化器不會評估連接選項,但我不認爲這將是這種情況。
如果您看到所有循環聯接,然後嘗試合併兩個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' 
0

您可以輕鬆地更換你的子查詢與聯接:

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是一個視圖 - 所以無論它是什麼都可能是減慢查詢速度。