我如何计算MySQL中帖子的评论和喜欢的数量?

我如何计算MySQL中帖子的评论和喜欢的数量?,mysql,Mysql,我有三个表,希望在获取帖子列表时使用“left join”和“groupby”来获取喜欢和评论的总数。我试过了 select posts.text, posts.id, count(comments.post_id) as comments, count(likes.post_id) as likes from posts left join likes on posts.id = likes.post_id left join comments on posts.id = comments.

我有三个表,希望在获取帖子列表时使用“left join”和“groupby”来获取喜欢和评论的总数。我试过了

select posts.text, posts.id, count(comments.post_id) as comments, 
count(likes.post_id) as likes from posts
left join likes on posts.id = likes.post_id
left join comments on posts.id = comments.post_id
group by posts.id

但它给出了一个错误的结果。我如何才能正确地执行此操作?

我想这可能会对您有所帮助:

select post.id, count(distinct comments.id), count(distinct likes.id)
from post
left join comments on post.id = comments.post_id
left join likes on post.id = likes.post_id
group by post.id

我建议将类似的计数存储在post表格中。此外,请解释您试图实现的目标。一种方法是举例说明你期望的结果。为什么结果会出错?不要忘记将其标记为已回答(在上/下票数下方)。