2010-07-15 148 views
3

我有多個用戶在多篇博文上發表評論。用戶可以在每篇博文中多次發表評論。我需要一個SQL查詢(sql server 2008)來獲得每個給定BlogPostId的用戶的最後評論。SQL Query爲每個博客帖子獲取最新的用戶評論,每個用戶只有一個評論?

可以說3個用戶在特定博客文章中共提交了10條評論。對於博客文章#1,用戶A提交了5條評論,用戶B提交了2條評論,並且用戶C提交了3條評論。

對於一個特定的BlogPostId(例如#1),我如何獲得每個用戶的最新評論,僅限於他們最近的評論(例如每個用戶一個評論)?

最終的結果應該產生三行

(User A) CommentId, BlogPostId, UserId, CommentData 
(User B) CommentId, BlogPostId, UserId, CommentData 
(User C) CommentId, BlogPostId, UserId, CommentData 
+1

你有沒有寫過我們可以幫助你的東西,還是你要求我們爲你寫整個東西? – msarchet 2010-07-15 15:46:59

+0

爲什麼不張貼表結構? – Kangkan 2010-07-15 15:46:59

回答

1

有很多很多方法可以做到這一點。使用排序功能:

with cte as (
    select *, row_number() over (partition by UserId order by PostedtDate desc) as rn 
    from Comments 
    where PostId = @postId) 
select * 
from cte 
where rn = 1; 

使用聚合和跨應用:

with cte as (
    select distinct UserId 
    from Comments 
    where PostId = @postId) 
select * 
from cte 
cross apply (
    select top(1) * 
    from Comments c 
    where c.UserId = cte.UserId 
    and c.PostId = @postId 
order by PostedDate desc); 

最終,真正重要的問題不是如何查詢該信息(這是微不足道的,你可能會得到10分鐘內有10個答案),但您如何設計您的模式以快速完成此查詢。

1

之一的幾種可能的解決方案,有一點對你的架構猜的,因爲你沒有在你的問題張貼信息(例如):

SELECT 
    C1.comment_id, 
    P.blog_post_id, 
    C1.user_id, 
    C1.comment_data 
FROM 
    Blog_Posts P 
LEFT OUTER JOIN Comments C1 ON 
    C1.blog_post_id = P.blog_post_id 
LEFT OUTER JOIN Comments C2 ON 
    C2.blog_post_id = C1.blog_post_id AND 
    C2.user_id = C1.user_id AND 
    C2.comment_date > C1.comment_date 
WHERE 
    P.blog_post_id = @blog_post_id AND 
    C2.comment_id IS NULL 

如果C2.comment_id爲null,那麼它一定是因爲以後的評論無法加入,所以C1必須是最新的。如果在時間上有確切的聯繫,那麼您可能會爲同一用戶收到兩條評論。

-1

選擇頂(1)CommentID,評論,用戶名,CREATEDATE從評論,其中BlogPostID = 1個 訂購CREATEDATE,用戶名,評論,CommentID通過用戶名

組確定這僅僅是直接從我的腦袋不知道您的數據庫 您需要爲您的博客帖子獲得所有評論 ,然後您需要按創建評論的日期進行排序asc或desc 然後您需要爲用戶進行分組,然後從列表中選擇第一個評論... 取決於你如何排序你也可以選擇最後一個,...

HTH

0

你可以試試這個:

select * from comments where blogpost_id = 3333 and comment_id in 
(select max(comment_id) from comments where blogpost_id = 3333 group by UserId) 
3

因爲它是MS SQL 2008,爲什麼不使用ROW_NUMBER()

WITH last_comment AS 
(
    SELECT ROW_NUMBER() OVER(PARTITION BY UserID ORDER BY DateAdded) as RowIndex, 
      * 
    FROM BlogPost B 
    WHERE BlogPostId = @BlogPostId 
) 
SELECT * 
FROM last_comment 
WHERE RowIndex = 1 
+0

這個作品太謝謝了! – 2010-07-15 16:11:58

相關問題