select a.post_id, a.total_comments
from
(
select post_id, 0 as total_comments
from posts
where post_id not in
(
select distinct id
from comments
)
union
select id, count(*)
from comments
group by id
) a
order by a.post_id desc;
SELECT post_id, COUNT(post_id)
FROM comment
WHERE post_id IN (1, 2, 3, 4, 5)
GROUP BY post_id
HAVING COUNT(post_id) >= 0
ORDER BY created_at DESC, post_id DESC
SELECT COUNT(post_id) AS 'count'
FROM posts LEFT JOIN comments on post.id = comments.post_id
WHERE post.id IN (1, 2, 3, 4, 5)
GROUP BY post_id ORDER BY count DESC, created_at DESC
4条答案
按热度按时间cbeh67ev1#
使用此查询:
插图:
更新:这里有一个不使用连接语法的版本。给出与上述相同的结果。
8cdiaqws2#
试试这个:
yyyllmsg3#
因为它是空的
看看这个
你需要从
posts
表中,有些帖子没有评论,所以post_id
不存在于comments
xmakbtuz4#
Having
在这种情况下没有帮助。看起来你对某些帖子没有任何评论。所以,您将不会从comments表中为这篇文章选择任何记录。你需要这样的东西: