Hi there coders around the world,
I\'m working on a project where users can do certain things and gain points for it. To simplify this question let\'s say we got 2 t
The idea is to ask, "how many players rank above @this_user":
select count(*) + 1 from
(
/* list of all users */
SELECT SUM( p.points ) AS sum_points
FROM user u
LEFT JOIN points p ON p.user_id = u.id
GROUP BY u.id
) x
/* just count the ones with higher sum_points */
where sum_points > (select sum(points) from points where user_id = @this_user)
Edited to make result 1-based instead of 0-based
SELECT q.*,
@r := @r + 1 AS rank
FROM (
SELECT @r := 0
) vars,
(
SELECT u.*,
SUM(p.points) AS sum_points
FROM
user u
LEFT JOIN
points p
ON p.user_id = u.id
GROUP BY
u.id
ORDER BY
sum_points DESC
) q