//表
+------+-------+
| user | score |
+------+-------+
| 2 | 500 |
| 3 | 780 |
| 4 | 50 |
| 5 | 250 |
| 6 | 650 |
+------+-------+
//当前的sql
SELECT @rn:=@rn+1 AS rank, user, score
FROM (
SELECT user,score
FROM scores
WHERE user = 2
ORDER BY score DESC
) t1, (SELECT @rn:=0) t2
上面的sql返回id = 2的用户的rank = 1,但rank是3.当没有添加where子句时是正确的。但我希望能够搜索特定用户并获得他的排名
答案 0 :(得分:3)
尝试这样的事情:
select * from
(SELECT @rn:=@rn+1 AS rank, user, score
FROM scores,
(SELECT @rn:=0) t2
ORDER BY score DESC) t
where user=2