a53*_*416 1 mysql sql database posts
我的问题类似于我已经尝试过解决方案的问题,但这对我的情况来说并不完全正确.
我有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 |
+----+---------+
Run Code Online (Sandbox Code Playgroud)
问题:
我想知道每个帖子得到多少票,并显示它们,以便投票率最高的帖子位于顶部.
Post ID Vote Count
+---------+-----------+
| 1 | 3 |
| 3 | 2 |
| 4 | 1 |
| 2 | 0 |
Run Code Online (Sandbox Code Playgroud)
SQL查询的目的是什么来实现这一目标?
select post_id, count(*)
from votes
group by post_id
order by count(*) desc
Run Code Online (Sandbox Code Playgroud)
编辑:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
278 次 |
| 最近记录: |