2012-06-27 73 views
1

我有一個表:用戶排名查詢

**user** 
id, name, points 

你建議我如何編寫一個查詢通過積分獲得用戶的地方。

例如:

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

用戶「莫妮卡」具有基於分第一名,「Jeniffer」 - 第4名等。

感謝您的諮詢!

編輯

我想要一個查詢,如:

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

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

回答

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

1
select * from user order by points desc 
+0

都能跟得上..我想查詢的結果應該是數量秩。 SELECT rank FROM user ........ WHERE id = 1應該返回'1' –

0

用這樣的方式:

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

如果你想獨自一人的排名第一持有人,你可以使用這個:

SELECT * FROM `user` ORDER BY `points` DESC LIMIT 1; 
0
set @rank := 0; 
select *, (@rank := @rank + 1) as rank 
from (select * from user order by points desc) x 
where id = 3 
+0

#1064 - 你的SQL語法有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在'* from(選擇* from customer order by points desc)'附近使用正確的語法x其中id = 3'在第1行 –

+0

@DmitryTeplyakov立即嘗試(我有明星錯誤的地方) – Bohemian

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 
0
with cte as(
select *,RANK() over(order by points desc) as rnk from user_ 
) 
select rnk [rank] from cte where id=3