2010-07-15 244 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

相关问题