嗨,我是SQL的新手,我正在试图弄清楚我将如何与大多数朋友(userId)获得前5名“乐队”,这就是我所拥有的;一个usertbl用userId作为PK然后是带有bandId作为PK的bandsTbl然后我有一个带有FK userId和bandId的表bandfriends。
bandfriends
userid | bandId
---------------
1 | 1
1 | 2
1 | 3
谢谢!
答案 0 :(得分:5)
SELECT TOP 5 bandId, fanCount
FROM
(SELECT bandId, COUNT(*) as fanCount
FROM bandfriends
GROUP BY bandId
ORDER BY COUNT(*) DESC)
答案 1 :(得分:2)
select top 5 b.b_name, count(friends) as numOfFriends
from bands b inner join link l on b.b_id = l.bands inner join
friends f on f.f_id = l.friends
group by b.b_name
order by numOfFriends desc
如果你有朋友表,乐队表和链接表,对我有用:)
答案 2 :(得分:0)
在mysql.org上阅读COUNT和GROUP BY
你会想要这样的东西(我还没有测试过):
SELECT bandId, COUNT(*) as fans FROM bandfriends
ORDER BY fans DESC
GROUP BY bandId
LIMIT 5;