我有一張表,其中包含我的帖子和我的意見。我們只發表一條評論,對評論沒有評論。現在,我們正在對帖子進行ajax請求,然後在另一個查詢中抓取註釋,使用父帖子ID來獲取適當的子註釋。SQL Server 2008線程評論系統 - 什麼更有效?
我想要做的就是將其整合到最高效的單一查詢系統中。
這讓我要麼使用CROSS APPLY,或UNION,如果我沒有記錯,但也有一些注意事項:
- 我們要選擇的十大職位,頂部2每個
- 帖子評論需要按降序列出
- 評論需要按升序排列
這裏上市是我們的CUR的例子租查詢的文章和評論:
帖子:
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:以可讀的方式格式化您的代碼! – Akhil 2012-03-22 22:34:47
對不起,在我準備好之前提交,但我沒有點擊按鈕。現在應該會好一點。 – ilikenwf 2012-03-22 22:42:38
*按鈕自己點擊!我發誓!* – 2012-03-22 23:04:06