2014-03-29 60 views
-1

你有什麼想法可以改進下面的sql select查詢嗎?即使在sql管理工作室中也需要一段時間才能獲得結果。所以,當我從網站打電話時,需要更長的時間。我獲得了前15名的成績,但仍然需要時間才能獲得成績。是否因爲子查詢?如何加速多個表中的select語句

SELECT top 15 t1.TagId, t1.TagName, 
(SELECT COUNT(*) FROM TagsToPost 
       WHERE TagsToPost.TagId=t1.TagId AND 
       EXISTS(SELECT * FROM Posts 
          WHERE PostId=TagsToPost.PostId AND 
          Posts.Time > '2014-01-01 00:00:00.000' AND 
          [email protected])) as myCount 

FROM Tags as t1 

WHERE (SELECT COUNT(*) FROM TagsToPost 
       WHERE TagsToPost.TagId=t1.TagId AND 
       EXISTS(SELECT * FROM Posts 
          WHERE PostId=TagsToPost.PostId AND 
          Posts.Time > '2014-01-01 00:00:00.000' AND 
          [email protected]))>1 

ORDER BY myCount DESC 
+0

@GordonLinoff,對不起,遺漏了這些細節。我現在在標籤中包含了sql-server。它隨着計數檢索標籤。用戶發佈問題,當他們提出問題時,他們選擇一個標籤。我使用TimePointId對不同時間間隔定義的問題進行分類。所以,我試圖檢索那個時間間隔(timepointid)的熱門標籤。 – renakre

回答

2

首先,你只需要運行一次子查詢:

SELECT top 15 * 
FROM (SELECT t1.TagId, t1.TagName, 
      (SELECT COUNT(*) 
       FROM TagsToPost 
       WHERE TagsToPost.TagId=t1.TagId AND 
        EXISTS (SELECT * 
          FROM Posts 
          WHERE PostId=TagsToPost.PostId AND 
            Posts.Time > '2014-01-01 00:00:00.000' AND 
            [email protected] 
          ) 
      ) as myCount 
     FROM Tags as t1 
    ) t 
WHERE COUNT(*) > 1 
ORDER BY myCount DESC; 

我不知道SQL Server將對其進行優化來消除產生一個結果集,所以這可能會切斷查詢時間半。

然後,您可以通過使用標準group byjoin消除exists一層:

 SELECT top 15 t.TagId, t.TagName, COUNT(*) as myCount 
     FROM tags t join 
      TagsToPost tp 
      on TagsToPost.TagId = t.TagId AND 
     WHERE EXISTS (SELECT 1 
        FROM Posts p 
        WHERE p.PostId = tp.PostId AND 
          p.Time > '2014-01-01 00:00:00.000' AND 
          [email protected] 
        ) 
     GROUP BY t.TagId, t.TagName 
     HAVING myCOunt > 1 
     ORDER BY myCount DESC; 

你可以做posts類似的東西。但創建一個索引Posts(PostId, TimePointId, Time)可能就足夠了。