2011-06-01 127 views
1

我想修改以下查詢來查找特定的videoid的排名,我沒有太多的運氣任何人都可以提出一個解決方案?MySQL查詢幫助查找排名ID

SELECT videoid wins/loses as win_loss, 
     @curRank := @curRank + 1 AS rank 
    FROM cb_video, 
     (SELECT @curRank := 0) r 
ORDER BY wins/loses DESC 

我試着做一個子查詢這樣的,但它失敗:

SELECT rank 
    FROM (SELECT videoid wins/loses as win_loss, 
       @curRank := @curRank + 1 AS rank 
      FROM cb_video, 
       (SELECT @curRank := 0) r 
     ORDER BY wins/loses DESC) 
WHERE videoid = 116 

還增加了視頻ID到WHERE無子查詢子句只是始終顯示排名是排名第一的位置,因爲它只有返回一行:

SELECT videoid wins/loses as win_loss, 
     @curRank := @curRank + 1 AS rank 
    FROM cb_video, 
     (SELECT @curRank := 0) r 
    WHERE videoid = 116 
ORDER BY wins/loses DESC 

任何想法如何限制結果到一個特定的ID,但仍然保持排名?僅供參考如果有幫助,我會保留兩列(勝利和失敗)。

+0

你的第二種方法似乎對我來說。你得到了什麼錯誤? – a1ex07 2011-06-01 01:54:34

+0

IME,如果表引擎是MyISAM,則不可信賴變量排名功能。數字會跳過... – 2011-06-01 02:46:16

回答

1
SELECT a.videoid, 
(SELECT COUNT(*) FROM cb_video b 
WHERE a.videoid !=b.videoid 
AND (b.wins/b.loses) > (a.wins/a.loses))+1 AS rank 
FROM cb_video a 
WHERE a.videoid = 116 
+0

a1ex07似乎工作,但我對你的勝利損失率的使用感興趣。您的查詢返回的排名爲6,而Arek的查詢返回的排名爲8。 – 2011-06-01 02:12:06

+0

這是因爲我的查詢返回比率大於當前的記錄數。例如,如果我們有4條記錄贏/輸是3,3,2,2,我的查詢返回最後一條記錄的排名= 3,Arek's - 4.運行我的查詢後,您將獲得兩個排名1和2排名= 3 – a1ex07 2011-06-01 02:38:46

+0

當有相同的比率時,這將產生重複的排名值 - 就像使用分析性的「DENSE_RANK」而不是「ROW_NUMBER」。 – 2011-06-01 02:45:10

1

嘗試這樣:

SELECT videoid, rank FROM (SELECT videoid, wins/loses as win_loss, @curRank := @curRank + 1 AS rank FROM cb_video, (SELECT @curRank := 0) r ORDER BY wins/loses DESC) s WHERE videoid = 116 
+0

這也適用。你的回報爲8分。我試圖找出哪一個更準確的是你的或上面的a1ex07s。 – 2011-06-01 02:14:14

1

如你所描述我測試過這種類似表格的創建簡單的子集... 它返回一個視頻和其實際最終排名整套...

select * 
    from (SELECT 
       videoid, 
       wins, 
       losses, 
       wins/losses,  
       @curRank := @curRank +1 Rank 
      FROM 
       cb_video, 
       (select @curRank := 0) r 
      order by 
       wins/losses desc) PreQuery 
    where 
     PreQuery.VideoID = 116 
+0

將表引擎更改爲MyISAM,然後查看您是否仍得到相同的結果。我打賭你不會...... – 2011-06-01 02:48:37