【发布时间】:2021-01-26 00:18:15
【问题描述】:
我已经研究了一天,并无法真正弄清楚。我正在制作一个用户可以发帖,其他用户可以回复和点赞的页面。
我有这三个表:帖子、回复和喜欢。仅供参考,它们都有不同的行数,请参阅下面的完整详细信息。
帖子表
post_id message
------- -------
1 This is post #1
2 This is post #2
3 This is post #3
回复表
reply_id post_id message
------- ------- -------
1 1 This is a reply to post #1
2 1 This is a reply to post #1
3 2 This is a reply to post #2
4 2 This is a reply to post #2
5 3 This is a reply to post #3
赞表
like_id post_id liked
------- ------- -------
1 1 Yes
2 1 Yes
3 1 Yes
4 2 Yes
5 2 Yes
6 3 Yes
7 3 Yes
这些是我的表格的结构。我需要实现的如下:
所有表已加入并统计
post_id total_replies total_likes
------- ------------- -----------
1 2 3
2 2 2
3 1 2
基本上,对于第一个帖子,它应该显示它有 2 个回复和 3 个喜欢。我似乎无法使用两个计数来做到这一点。它给了我错误的数字。
select posts.post_id, count(replies.post_id) as total_replies, count(likes.post_id) as total_likes from posts
inner join replies on posts.post_id = replies.post_id
inner join likes on posts.post_id = likes.post_id
group by posts.post_id
【问题讨论】: