mySQL “Rank in Highscore”-Query

后端 未结 2 832
滥情空心
滥情空心 2021-01-03 11:52

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

相关标签:
2条回答
  • 2021-01-03 12:33

    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

    0 讨论(0)
  • 2021-01-03 12:35
    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
    
    0 讨论(0)
提交回复
热议问题