SQL grouping - Show only 5 comments per post

2019-09-14 12:37发布

To make thing easier to understand lets take the following example: I want to show only the top 5 comments for a specific post (Like the post on facebook where people cant comment them). How could I do this in SQL if you take this query

select tblPost.id,tblComment.id
from tblComment,tblPost
where tblPost.id = tblComment.postid

if I try select top 5 tblComment.id... it will return only 5 results and not all the post with only a maximum of 5 comment per post.

2条回答
The star\"
2楼-- · 2019-09-14 13:16
select
   *
FROM
   tblPost P
   OUTER APPLY
   (SELECT TOP 5 * FROM tblComment C  
      WHERE P.id = C.postid
      ORDER BY something) inline
查看更多
做自己的国王
3楼-- · 2019-09-14 13:33

Try using ROW_NUMBER, assuming you are using a database that supports it:

SELECT id, postid
FROM tblComment
(
    SELECT 
        id,
        postid,
        ROW_NUMBER() OVER (PARTITION BY postid ORDER BY id DESC) AS rn
    FROM tblComment
) AS T1
WHERE rn <= 5
查看更多
登录 后发表回答