按计数(*)子查询排序

时间:2016-03-04 02:12:43

标签: mysql sql

对于子查询完全不熟悉,我正在尝试按表格showcase中的帖子排序(按降序排列)并且不确定如何。

SELECT *
FROM showcase
ORDER BY 
    (select count(*)
     from comments)
DESC

3 个答案:

答案 0 :(得分:1)

如果您只需要ID,请为每个组分组并计算行数

select showcase.id
from showcase left join comments on comments.item_id = showcase.id
group by showcase.id
order by count(showcase.id) desc

答案 1 :(得分:0)

我们需要使用group with count:

select s.postId, count(c.commentid) as comments
from showcase s join comment c on s.postId = c.postId
group by s.postId
order by comments desc

答案 2 :(得分:0)

  

您可以尝试更适合查询的联接查询。

SELECT `showcase`.*, count(`comments`.`item_id`) as item_id FROM `showcase`
LEFT JOIN `comments`
ON `showcase`.`id`, `comments`.`item_id`
ORDER BY item_id DESC

让我知道它是否有效。