【发布时间】:2014-12-25 10:21:45
【问题描述】:
我有两个数据库表。 帖子和投票。
**posts table;**
id | user_id | content
1 | 1 | first post
2 | 1 | second post
3 | 1 | third
**votes table;**
vote | post_id
------+---------
t | 1
t | 2
t | 2
t | 2
f | 2
t | 3
t | 3
t | 3
vote is a boolean with values true or false
现在我想查找按降序排序的所有帖子,以便结果反映投票(赞成票数(真票)-反对票数(假票))。
SELECT posts.*, count(votes.vote is true) - count(votes.vote is false) as vote_count
FROM "posts"
LEFT JOIN votes AS votes ON votes.post_id = posts.id
GROUP BY posts.id
ORDER BY vote_count DESC LIMIT 100;
上述查询返回结果,但 vote_count 字段中的所有值都是 0(零)。 (我知道我是个菜鸟!)
在这种情况下正确的查询是什么?
想要的结果是('()'内的值仅供参考):
id | votes | content
----+-----------------------
3 | 3(3-0)| third
2 | 2(3-1)| second post
1 | 1(1-0)| first post
谢谢。
附: - 如果您也可以给我相应的rails查询,将会有很大帮助。
【问题讨论】:
标签: sql ruby-on-rails database relational-database