[英]Select the top 5 most frequent rows and query data from another table
Let's say I have 2 tables on my database, 假设我的数据库中有2个表,
The first one: 第一个:
TABLE "SONGS"
+----+-------+--------+
| id | title | artist |
+----+-------+--------+
| 1 | song1 | blah |
| 2 | song2 | wut? |
| 3 | song3 | random |
+----+-------+--------+
And another one: 还有一个:
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 |
+----+---------+--------+
I was trying to have my script query out the most frequent song_id
from the table plays
then join it with the title
and artist
in the songs
table to make the music chart for a radio station, but so far no luck on getting the result. 我试图让脚本从表plays
查询出最频繁的song_id
,然后将其与songs
表中的title
和artist
一起加入,以制作广播电台的音乐排行榜,但到目前为止,运气不好。
This is the expected result: 这是预期的结果:
[
{"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}
]
Thank you in advance. 先感谢您。
You can do a regular JOIN between the tables, counting the number of rows per id/artist/title and ordering by that; 您可以在表格之间进行常规的JOIN,计算每个ID /艺术家/标题的行数并以此排序;
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
An SQLfiddle to test with . 要使用进行测试的SQLfiddle 。
To just get the play order with just an id, no need to join; 只需一个ID即可获得播放顺序,无需加入;
SELECT song_id, COUNT(*) plays
FROM plays p
GROUP BY song_id
ORDER BY plays DESC
Another SQLfiddle . 另一个SQLfiddle 。
To just get the top 5 results, a LIMIT 5
can be appended added to either query. 为了仅获得前5个结果,可以将LIMIT 5
添加到任一查询中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.