查询:
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;
在Postgresql中返回n条记录:
count_all | post_id -----------+--------- 1 | 6 3 | 4 3 | 5 3 | 1 1 | 9 1 | 10 (6 rows)
我只想检索返回的记录数: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;
我想你只需要COUNT(DISTINCT post_id)从投票。
原文链接:https://www.f2er.com/postgresql/193146.html请参阅http://www.postgresql.org/docs/current/static/sql-expressions.html中的“4.2.7。汇总表达式”部分。