-1

您知道如何改进以下 sql 选择查询吗?即使在 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
4

1 回答 1

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 是否会对其进行优化以消除生成一个结果集,因此这可能会将查询时间缩短一半。

exists然后,您可以通过使用标准group 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)

于 2014-03-29T16:22:18.237 回答