我有一个如下所示的mysql表:
id name points
1 john 4635
3 tom 7364
4 bob 234
6 harry 9857
我基本上想要在不选择所有用户的情况下获得个人用户排名。我只想按id选择一个用户,并获得用户排名,这取决于他们拥有的点数。
例如,通过id 3选择等级2来获取tom。
干杯
EEF
答案 0 :(得分:18)
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
答案 1 :(得分:2)
@Quassnoi的解决方案将失败。以下是解决问题的解决方案:
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
答案 2 :(得分:0)
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