SQL Server 2008线程评论系统 - 什么更有效?

时间:2012-03-22 22:32:45

标签: sql sql-server tsql

我有一张包含我的帖子和评论的表格。我们只对一个评论进行深入评论,对评论没有评论。现在,我们正在对帖子进行ajax请求,然后在另一个查询中抓取评论,使用父帖子ID来获取相应的子评论。

我想要做的是将其整合到我能够最有效的单一查询系统中。

如果我没有弄错的话,这会让我使用CROSS APPLY或UNION,但有一些警告:

  • 我们希望选择前10个帖子,并为每个
  • 选择前2个评论
  • 帖子需要按降序列出
  • 评论需要按升序列出

以下是我们当前对帖子和评论的查询示例:

文章:

 SELECT TOP 10 ForumPostID, ForumID, ContentText, Hidden, S.Firstname, S.Lastname,   
 CONVERT(VARCHAR(30),DATEADD(hh,CASE
       WHEN DD.StartDate IS NOT NULL THEN 5 ELSE 6 
       END,
 FP.PostDate),126)+'Z' AS PostDate, 
 PostDate AS UglyTime, TopPostID, 
 (SELECT COUNT(*) FROM Admin.dbo.ForumPosts WHERE TopPostID = FP.ForumPostID) AS     
 'CommentCount',
 (SELECT COUNT(*) FROM Admin.dbo.ForumLikes WHERE ForumPostID = FP.ForumPostID) AS 'Likes',      
 CASE (SELECT COUNT(*) FROM Admin.dbo.ForumLikes WHERE ForumPostID = FP.ForumPostID AND    
      Authuser = FP.Authuser) WHEN 0 THEN 'Like' ELSE 'You liked this.' END AS 'LikeText' 
 FROM Admin.dbo.ForumPosts FP 
 INNER JOIN Student.dbo.Student S 
      ON S.StudentUID = FP.Authuser
 INNER JOIN Admin.dbo.DayLightSavingsDates DD 
      ON FP.PostDate BETWEEN DD.StartDate AND DD.EndDate
 WHERE FP.ForumPostID NOT IN ( SELECT Top 0 ForumPostID FROM Admin.dbo.ForumPosts FP2 ORDER BY 
 FP2.ForumPostID DESC) 
 AND FP.Hidden = 'N' AND FP.ContentText <> '' 
 AND FP.PostType = 'post' 
 ORDER  BY FP.PostDate DESC 

评论:

SELECT TOP 50 ForumPostID, ForumID, ContentText, Hidden, S.Firstname, S.Lastname, 
CONVERT(VARCHAR(30),DATEADD(hh,CASE
      WHEN DD.StartDate IS NOT NULL THEN 5 ELSE 6 END,
FP.PostDate),126)+'Z' AS PostDate,
PostDate AS UglyTime, TopPostID,
(SELECT COUNT(*) FROM Admin.dbo.ForumPosts WHERE TopPostID = FP.ForumPostID) AS     
      'CommentCount', 
(SELECT COUNT(*) FROM Admin.dbo.ForumLikes WHERE ForumPostID = FP.ForumPostID) AS 'Likes',
CASE (SELECT COUNT(*) FROM Admin.dbo.ForumLikes WHERE ForumPostID = FP.ForumPostID AND 
     Authuser = FP.Authuser) WHEN 0 THEN 'Like' ELSE 'You liked this.' END AS 'LikeText' 
FROM Admin.dbo.ForumPosts FP 
INNER JOIN Student .dbo.Student S 
ON S.StudentUID = FP.Authuser 
INNER JOIN Admin.dbo.DayLightSavingsDates DD ON FP.PostDate BETWEEN DD.StartDate AND DD.EndDate 
WHERE FP.ForumPostID NOT IN 
    ( SELECT Top 0 ForumPostID FROM Admin.dbo.ForumPosts FP2 ORDER BY FP2.ForumPostID DESC) 
AND FP.ForumPostID IN 
   (SELECT Top 2 ForumPostID FROM Admin.dbo.ForumPosts  FP3 WHERE FP3.TopPostID = FP.TopPostID 
       ORDER BY FP3.PostDate DESC) 
AND FP.Hidden = 'N' 
AND FP.ContentText <> '' 
AND FP.PostType = 'comment' 
AND FP.TopPostID IN ( 373, 371, 370, 369, 368, 367, 366, 365, 364, 363 )
ORDER BY FP.ForumPostID ASC 

1 个答案:

答案 0 :(得分:0)

这里可以给出的最重要的建议是你需要查看执行计划。我不知道如何解决这个问题。查询过于复杂,无法提供具体建议。

但有一件事:你有很多表达式,比如“(SELECT COUNT(*)FROM Admin.dbo.ForumPosts WHERE TopPostID = FP.ForumPostID)”。 SQL Server查询优化器在计算中使用此类表达式时遇到问题。它有时无法将它们转换为普通连接,从而阻止了大量优化。您可能希望将它们转换为连接。然而,就目前我所知,IN条款是安全的。