Top 5 comments from a specific post. How to write my SQL

发布于 2022-09-06 08:33:38 字数 1182 浏览 13 评论 0

I want to show only the top 5 comments for a specific post (Like the post on facebook where people cant comment them).

gbn was kind enough to help figure out that issue by doing the following:

select
   *
FROM
   tblPost P
   OUTER APPLY
   (SELECT TOP 5 * FROM tblComment C  
      WHERE P.id = C.postid
      ORDER BY something) inline

But since I'm no sql grand master I would need your help to put that into my real sql statement.

SELECT *
FROM
memberactions INNER JOIN
actions ON memberactions.actionid = actions.id INNER JOIN
members ON memberactions.memberid = members.id LEFT OUTER JOIN
members members_2 INNER JOIN
actioncomments ON members_2.id = actioncomments.memberid INNER JOIN
comments ON actioncomments.commentid = comments.id ON actions.id = actioncomments.actionid

So my question is could you rearrange my sql to put the OUTER APPLY in my real sql statement.

Assuming that my table comments reprensent tblComment and that actioncomments represent the table tblPost

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时光暖心i 2022-09-13 08:33:38

There does not seem to be a need for the member_2 table at all, but this is a faithful representation of what you had (preserving member_2)

SELECT *
FROM memberactions
INNER JOIN actions
    ON memberactions.actionid = actions.id
INNER JOIN members
    ON memberactions.memberid = members.id
OUTER APPLY (
    select top(5) *
    FROM actioncomments
    inner join comments ON actioncomments.commentid = comments.id
    inner join members members_2 ON members_2.id = actioncomments.memberid
    WHERE actions.id = actioncomments.actionid
    order by comments.id desc) comments
趁微风不噪 2022-09-13 08:33:38
SELECT *
FROM
memberactions 
INNER JOIN actions 
ON memberactions.actionid = actions.id 
INNER JOIN members 
ON memberactions.memberid = members.id 
LEFT OUTER JOIN members members_2 
    INNER JOIN actioncomments 
    ON members_2.id = actioncomments.memberid 
    OUTER APPLY  

    (SELECT TOP 5 * FROM comments C  
          WHERE actioncomments.commentid = comments.id 
      ORDER BY something)


ON actions.id = actioncomments.actioni

still don't know what you want to order by

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文