MySQL, Get users rank

自古美人都是妖i 提交于 2019-11-26 09:09:58

问题


I have a mysql table like below:

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

I basically want to get an individual user rank without selecting all of the users. I only want to select a single user by id and get the users rank which is determined by the number of points they have.

For example, get back tom with the rank 2 selecting by the id 3.

Cheers

Eef


回答1:


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



回答2:


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



回答3:


 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


来源:https://stackoverflow.com/questions/1293817/mysql-get-users-rank

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!