用户排名查询

时间:2012-06-27 04:35:41

标签: mysql sql

我有一张桌子:

**user**
id, name, points

您能否建议我如何撰写查询以逐点获取用户。

例如:

1, 'David', 5
2, 'Dmitry', 10
3, 'Monica', 15
4, 'Jeniffer', 7
5, 'Andy', 12

用户'Monica'以积分排名第一,'Jeniffer'排名第四,依此类推。

感谢您的建议!

修改

我想要一个类似的查询:

SELECT rank FROM user ... WHERE id = 3;
rank |
1

SELECT rank FROM user ... WHERE id = 5;
rank |
2

6 个答案:

答案 0 :(得分:1)

select * from user order by points desc

答案 1 :(得分:1)

请尝试以下方法:

SELECT
   id,rank, name,point 
FROM (
    SELECT id,
        name,
        point,  
        @rank := @rank + 1 as rank        
    FROM (
      SELECT * from tblA ORDER by point desc) As a, 
    (SELECT @rank := 0) AS vars      

) T 
WHERE id=1

http://sqlfiddle.com/#!2/581fc/9

答案 2 :(得分:1)

试试这个:

select t.rank from (
      select @i := @i + 1 as rank, id, name, points
        from MyUser x,(SELECT @i:=0) foo 
    order by x.points desc) T
 where T.id = 3

答案 3 :(得分:0)

使用这种方式:

SELECT * FROM `user` ORDER BY `points` DESC;

如果你想单独获得第一名,你可以使用:

SELECT * FROM `user` ORDER BY `points` DESC LIMIT 1;

答案 4 :(得分:0)

set @rank := 0;
select *, (@rank := @rank + 1) as rank
from (select * from user order by points desc) x
where id = 3

答案 5 :(得分:0)

with cte as(
select *,RANK() over(order by points desc) as rnk from user_ 
)
select rnk [rank] from cte where id=3