假设我的数据库中有2个表,
第一个:
TABLE "SONGS"
+----+-------+--------+
| id | title | artist |
+----+-------+--------+
| 1 | song1 | blah |
| 2 | song2 | wut? |
| 3 | song3 | random |
+----+-------+--------+
还有一个:
TABLE "PLAYS"
+----+---------+--------+
| id | song_id | time |
+----+---------+--------+
| 1 | 2 | 13:04 |
| 2 | 1 | 13:07 |
| 3 | 1 | 14:30 |
| 4 | 3 | 14:41 |
| 5 | 2 | 14:59 |
| 6 | 1 | 15:32 |
+----+---------+--------+
我试图让我的脚本从表song_id
中查询最常见的plays
,然后将其与title
中的artist
和songs
一起加入}表格为广播电台制作音乐图表,但到目前为止还没有运气得到结果。
这是预期的结果:
[
{"song_id": 1, "title": "song1", "artist": "blah", "plays": 3},
{"song_id": 2, "title": "song2", "artist": "wut?", "plays": 2},
{"song_id": 3, "title": "song3", "artist": "random", "plays": 1}
]
提前谢谢。
答案 0 :(得分:2)
你可以在表之间进行常规的JOIN,计算每个id / artist / title的行数和按顺序排序;
SELECT s.id, s.title, s.artist, COUNT(*) plays
FROM songs s
JOIN plays p
On s.id = p.song_id
GROUP BY s.id, s.title, s.artist
ORDER BY plays DESC
只需一个id就可以获得播放顺序,无需加入;
SELECT song_id, COUNT(*) plays
FROM plays p
GROUP BY song_id
ORDER BY plays DESC
要获得前5个结果,可以将LIMIT 5
添加到任一查询中。