如何加速多个表中的select语句

时间:2014-03-29 16:16:59

标签: sql sql-server select-query

您是否知道如何改进以下sql select查询?即使在sql management studio中也需要一段时间才能获得结果。因此,当我从网站上调用它时需要更长的时间。我获得了前15名的成绩,但仍需要时间才能获得结果。是因为子查询吗?

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
                             Posts.TimePointId=@TimePointId)) 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
                             Posts.TimePointId=@TimePointId))>1

ORDER BY myCount DESC

1 个答案:

答案 0 :(得分: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
                                  Posts.TimePointId=@TimePointId
                           )
             ) as myCount
      FROM Tags as t1
     ) t
WHERE COUNT(*) > 1
ORDER BY myCount DESC;

我不确定SQL Server是否会优化它以消除生成一个结果集,因此这可能会将查询时间缩短一半。

然后,您可以使用标准existsgroup by消除一级join

      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
                          p.TimePointId=@TimePointId
                   )
      GROUP BY t.TagId, t.TagName
      HAVING myCOunt > 1
      ORDER BY myCount DESC;

您可以使用posts执行类似操作。但是创建索引Posts(PostId, TimePointId, Time)可能就足够了。