MySQL, Get users rank

后端 未结 3 1987
余生分开走
余生分开走 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: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
    

提交回复
热议问题