MySQL,获取用户排名
我有一个如下所示的MySQL表:
id name points 1 john 4635 3 tom 7364 4 bob 234 6 harry 9857
我基本上想得到一个单独的用户排名,而不是select所有的用户。 我只想通过id来select一个用户,并根据他们拥有的点数来获得用户的排名。
例如,回到汤姆与秩3select由id 3。
干杯
EEF
SELECT uo.*, ( SELECT COUNT(*) FROM users ui WHERE (ui.points, ui.id) >= (uo.points, uo.id) ) AS rank FROM users uo WHERE id = @id
密级:
SELECT uo.*, ( SELECT COUNT(DISTINCT ui.points) FROM users ui WHERE ui.points >= uo.points ) AS rank FROM users uo WHERE id = @id
@Quassnoi解决scheme将失败的情况下,关系。 这是解决scheme,将在情况下工作:
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
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