2014-06-14 66 views
-4

我有一個參與者表:查找排名的sql

userid name 
1  John 
2  Sam 
3  Harry 

而且有比賽表:

contestid contestname 
1   abc 
2   def 
3   ghi 

得分表看起來像這樣:

id contestid userid score 
1 1   1  200 
2 1   2  300 
3 1   3  250 
4 2   1  500 
5 2   2  400 
6 3   2  800 

現在,考慮到userid,我需要在所有比賽中找出他的排名。 排名應該基於比賽和分數。

輸出應該是這樣的userid=1

contestid rank 
1   3 
2   1 
3   Nil 

我怎樣才能得到這個輸出?

+1

還有,你試過了ISN」工作ING?這是一個簡單的'LEFT(OUTER)JOIN'查詢。 –

回答

0


如果你需要通過排名分數和比賽那就試試這個


SET @rank := 0; 
SET @prev := NULL; 

SELECT contestid,userid,score,Rank FROM 
(
SELECT contestid,userid,score,@rank := IF(@prev = contestid, @rank + 1, 1) AS rank, 
     @prev := contestid 
FROM scores ORDER BY contestid, score DESC 
) S Where userid = 1 

FIDDLE DEMO


2.如果您需要它排名得分然後嘗試這個


SELECT contestid,userid,score, FIND_IN_SET(score, 
     (SELECT GROUP_CONCAT(score ORDER BY score DESC) FROM scores)) AS rank 
FROM scores 
Where UserId = 1 

Fiddle Demo



3.如果你想UserName和競賽名稱那就試試這個


SELECT C.contestname,P.name,S.score, FIND_IN_SET(S.score, 
     (SELECT GROUP_CONCAT(score ORDER BY score DESC) FROM scores)) AS rank 
FROM scores S Join participant P ON P.userid =C.userid 
       Join contest C ON C.contestid = S.contestid 
Where UserId = 1 
+0

在您的查詢中,userid 1的用戶在Fiddle示例表的比賽1中獲得了排名6。 –

+0

@ user2779912你是否需要通過評分或得分和比賽來排名? –

+0

分數和比賽。應根據相應的分數爲每場比賽評估等級。感謝幫助。 –