【问题标题】:How can I count the number of comments and likes that a post has in MySQL?我如何计算一个帖子在 MySQL 中的评论和喜欢的数量?
【发布时间】:2020-12-23 19:45:21
【问题描述】:

posts table

comments table

likes table

我有三个表,我想在获取帖子列表时使用“左连接”和“分组依据”来获取喜欢和 cmets 的总数。我试过了

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

但它给出了错误的结果。如何正确操作?

【问题讨论】:

  • 我建议将点赞数存储在 post 表中
  • 另外,请解释您要完成的工作。一种方法是举例说明您期望的结果。为什么你得到错误的结果?

标签: mysql


【解决方案1】:

我认为这可能对你有用:

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

【讨论】:

  • 不要忘记将其标记为已回答(在赞成/反对票下方)。
猜你喜欢
  • 2018-12-14
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
  • 2013-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多