【发布时间】:2021-08-18 03:51:36
【问题描述】:
我有三张桌子:
帖子:
id | title
------------------
1 | post1
2 | post2
3 | post3
4 | post4
评论:
post_id | content
-----------------------
1 | asd
1 | dsad
1 | awtihaw
2 | aaaaa
2 | bbbbbbbb
4 | asdasd
投票:
post_id | value
-----------------------
1 | 1
2 | 1
2 | -1
3 | 1
3 | 1
3 | 1
3 | -1
问题
我需要计算每个帖子有多少个cmet和多少个赞。
这是我的查询:
SELECT posts.id, COUNT(comments.post_id) as comments, SUM(votes.value) as votes
FROM posts
LEFT JOIN comments ON posts.id = comments.post_id
LEFT JOIN votes ON posts.id = votes.post_id
GROUP BY posts.id
ORDER BY posts.id
事实上我得到了一个结果,但是在结果中它说
post ID 为 1 有 3 票 和 3 cmets
实际上它只有一票和三个 cmets。 如何正确连接三个表以显示正确的结果?我需要能够仅在查询中执行此操作,最好只在一个查询中执行此操作。
【问题讨论】:
标签: sql postgresql aggregate-functions