我的问题是similar to this one,我已经尝试了解决方案,但这对我的方案来说并不完全正确。
我有2张桌子:投票和帖子。这是一个基本草图:
`posts`
----+------------------------------------------------------------------------+
| ID | post_title |
+----+-----------------------------------------------------------------------+
| 1 | Hello world. |
| 2 | This is a post! |
| 3 | What is the meaning of life? |
| 4 | Looking for a good time? |
+----+-----------------------------------------------------------------------
`votes`
+----+---------+
| ID | post_id |
+----+---------+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 3 |
| 5 | 3 |
| 6 | 4 |
+----+---------+
问题:
我想知道每个帖子得到多少票,并显示它们,以便投票率最高的帖子位于顶部。
Post ID Vote Count
+---------+-----------+
| 1 | 3 |
| 3 | 2 |
| 4 | 1 |
| 2 | 0 |
实现此目标的SQL查询是什么样的?
答案 0 :(得分:5)
select post_id, count(*)
from votes
group by post_id
order by count(*) desc
编辑:
select v.post_id, count(*)
from votes v INNER JOIN posts p ON v.post_id = p.id
group by v.post_id
order by count(*) desc
答案 1 :(得分:3)
SELECT post_id, COUNT(*) AS tally
FROM votes
GROUP
BY post_id
UNION
SELECT ID AS post_id, 0 AS tally
FROM posts
WHERE ID NOT IN (SELECT post_id FROM votes);
答案 2 :(得分:0)
如果你想在没有UINON的情况下包含零投票数的帖子,你可以做
SELECT
p.id,
SUM(CASE WHEN v.post_id IS NOT NULL THEN 1 ELSE 0 END) AS tally
FROM
posts p
LEFT JOIN votes v
ON v.post_id = p.id
ORDER BY
SUM(CASE WHEN v.postid IS NOT NULL THEN 1 ELSE 0 END) DESC
GROUP
BY p.id
此处需要SUM / CASE,因为COUNT(NULL)= 1
由于您的结构距离an example很近,您可以查看data.SE