查询:
SELECT COUNT(*) as count_all, posts.id as post_id FROM posts INNER JOIN votes ON votes.post_id = posts.id GROUP BY posts.id;
返回nPostgresql中的记录:
n
count_all | post_id -----------+--------- 1 | 6 3 | 4 3 | 5 3 | 1 1 | 9 1 | 10 (6 rows)
我只想检索返回的记录数:6。
6
我使用了一个子查询来实现我想要的,但这似乎不是最佳的:
SELECT COUNT(*) FROM ( SELECT COUNT(*) as count_all, posts.id as post_id FROM posts INNER JOIN votes ON votes.post_id = posts.id GROUP BY posts.id ) as x;
如何在PostgreSQL中获得这种上下文中的记录数?
我想你只需要COUNT(DISTINCT post_id) FROM votes。
COUNT(DISTINCT post_id) FROM votes
请参阅http://www.postgresql.org/docs/current/static/sql- expressions.html中的“ 4.2.7。聚合表达式”部分。
编辑:根据Erwin的评论更正了我的粗心大意的错误。