简体   繁体   中英

mySQL query: order by group points by sum of join member points

I got 2 tables which are linked. GROUPS can have multiple USERS and USERS can be in multiple GROUPS.

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
----------------

Now I want to rank the groups by the points of their members. Result:

GROUP_USER
|rank| group_name  | user_points  |
-----------------------------------
|1   |  Koalas     |  10
|2   |  Hornets    |  7 
|3   |  Grizzlies  |  6

Don´t really know how to start.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM