Sql server SQL查询以获取每个博客帖子的最新用户评论,每个用户只能有一条评论?

Sql server SQL查询以获取每个博客帖子的最新用户评论,每个用户只能有一条评论?,sql-server,sql,Sql Server,Sql,我有多个用户在多个博客帖子上提交评论。用户可以在每篇博客文章上多次发表评论。我需要一个SQL查询SQL server 2008来获取每个用户的最后一条评论 假设3个用户在一篇特定的博客文章上总共提交10条评论。对于博客帖子1,用户A提交了5条评论,用户B提交了2条评论,用户C提交了3条评论 对于一个特定的blogposted,例如1,我如何获得每个用户的最新评论,将其限制为他们的最新评论,例如,每个用户一条评论 最终结果应产生三行,例如 (User A) CommentId, BlogPostI

我有多个用户在多个博客帖子上提交评论。用户可以在每篇博客文章上多次发表评论。我需要一个SQL查询SQL server 2008来获取每个用户的最后一条评论

假设3个用户在一篇特定的博客文章上总共提交10条评论。对于博客帖子1,用户A提交了5条评论,用户B提交了2条评论,用户C提交了3条评论

对于一个特定的blogposted,例如1,我如何获得每个用户的最新评论,将其限制为他们的最新评论,例如,每个用户一条评论

最终结果应产生三行,例如

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

几种可能的解决方案之一,由于您没有在问题中发布该信息,因此对您的模式进行了一些猜测:

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为空,则必须为空,因为不能加入后续注释,因此C1必须是最新的。如果在时间上有一个确切的平局,您可能会为同一用户返回两条评论。

从BlogPostID=1的评论中选择前1位的CommentID、Comment、UserName、CreateDate 按CreateDate、用户名、注释、注释ID排序 按用户名分组

好的,这是我直接想到的,不知道你的数据库 你需要得到你博客帖子的所有评论 然后,您需要按创建注释的日期(asc或desc)进行排序 然后你需要为用户分组,并从列表中选择第一个。。。 根据您的排序方式,您也可以选择最后一个

HTH

您可以尝试以下方法:

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

既然是MS SQL 2008,为什么不使用行号

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

有很多方法可以做到这一点。使用排名函数:

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个答案,而是你如何设计你的模式来快速查询。

你是否已经编写了我们可以帮助你的内容,还是你要我们为你写整件事?为什么不把表格结构贴出来?