我有两个数据库表。 发布和投票。
**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
现在我想查找按降序排序的所有帖子,以便结果反映投票数(upvotes数(真实投票数) - downvotes数(虚假投票数))。
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(零)。 (我知道我是NOOB!)
在这种情况下,正确的查询是什么?
所需的结果是('()'中的值仅供参考):
id | votes | content
----+-----------------------
3 | 3(3-0)| third
2 | 2(3-1)| second post
1 | 1(1-0)| first post
感谢。
P.S。 - 如果你能给我相应的铁路查询也会有很大的帮助。
答案 0 :(得分:3)
尝试使用CASE进行内部联接,如下所示:
SELECT SUM(CASE WHEN vote = 't' then 1 ELSE -1 END) AS Votes, post_id, content
FROM votes v INNER JOIN posts p ON p.id = v.post_id
GROUP BY post_id
ORDER BY SUM(CASE WHEN vote = 't' then 1 ELSE -1 END) DESC