MySQL, Get users rank

后端 未结 3 1971
余生分开走
余生分开走 2020-11-28 12:39

I have a mysql table like below:

id     name     points
1      john     4635
3      tom      7364
4      bob      234
6      harry    9857

相关标签:
3条回答
  • 2020-11-28 12:44
    SELECT  uo.*, 
            (
            SELECT  COUNT(*)
            FROM    users ui
            WHERE   (ui.points, ui.id) >= (uo.points, uo.id)
            ) AS rank
    FROM    users uo
    WHERE   id = @id
    

    Dense rank:

    SELECT  uo.*, 
            (
            SELECT  COUNT(DISTINCT ui.points)
            FROM    users ui
            WHERE   ui.points >= uo.points
            ) AS rank
    FROM    users uo
    WHERE   id = @id
    
    0 讨论(0)
  • 2020-11-28 12:45

    Solution by @Quassnoi will fail in case of ties. Here is the solution that will work in case of ties:

    SELECT *,
    IF (@score=ui.points, @rank:=@rank, @rank:=@rank+1) rank,
    @score:=ui.points score
    FROM users ui,
    (SELECT @score:=0, @rank:=0) r
    ORDER BY points DESC
    
    0 讨论(0)
  • 2020-11-28 12:54
     SET @rownum := 0;
     SELECT rank, score FROM ( SELECT @rownum := @rownum +1 AS rank, `score` ,`user_id`
     FROM leaderboard 
     ORDER BY  `score` DESC , `updated_timestamp` ) as result WHERE `user_id`=$user_id
     LIMIT 1
    
    0 讨论(0)
提交回复
热议问题