我有两个链接的表。 GROUPS可以有多个用户,USERS可以有多个用户。
GROUPS
|id| name |
----------------
|1| Koalas |
|2| Grizzlies |
|3| Hornets |
----------------
USERS
|id| firstName | points |
----------------
|1| Bob | 2
|2| Hans | 4
|3| Jerome | 1
|4| Katy | 6
----------------
GROUP_USER
|id| group_id | user_id |
--------------------------
|1| 1 | 2
|2| 1 | 4
|3| 2 | 1
|4| 2 | 2
|5| 3 | 3
|6| 3 | 4
----------------
现在我想按照其成员的分数对这些群体进行排名。 结果:
GROUP_USER
|rank| group_name | user_points |
-----------------------------------
|1 | Koalas | 10
|2 | Hornets | 7
|3 | Grizzlies | 6
不知道如何开始。
答案 0 :(得分:1)
select @rank := @rank + 1 as rank, name, user_points
from
(
select g.name,
sum(u.points) as user_points
from groups g
left join group_user gu on gu.group_id = g.id
left join users u on gu.user_id = u.id
group by g.name
order by user_points desc
) tmp
cross join (select @rank := 0) r