【发布时间】:2020-09-14 13:50:02
【问题描述】:
我有 2 张桌子、帖子和 cmets
帖子
Post_Id
Content
评论
Comment_id
Content
Post_id
我想获取帖子,但我希望 cmets 数量最多的帖子出现在顶部。 请问我该怎么做
【问题讨论】:
标签: mysql sql count subquery sql-order-by
我有 2 张桌子、帖子和 cmets
帖子
Post_Id
Content
评论
Comment_id
Content
Post_id
我想获取帖子,但我希望 cmets 数量最多的帖子出现在顶部。 请问我该怎么做
【问题讨论】:
标签: mysql sql count subquery sql-order-by
您可以将相关子查询放在order by 子句中:
select p.*
from posts p
order by (select count(*) from comments c where c.post_id = p.post_id) desc
另一种选择是在子查询中预聚合。如果您想显示 cmets 的计数,这也很方便:
select p.*, coalesce(c.cnt_comments, 0) cnt_comments
from posts p
left join (select post_id, count(*) cnt_comments from comments group by post_id) c
on c.post_id = p.post_id
order by coalesce(c.cnt_comments, 0) desc
【讨论】: