2011-05-12 84 views
0
def best_drivers(limit = 10) 
    lost = 'SELECT COUNT(c.id) FROM challenges AS c 
      WHERE (c.challenger_id = u.id AND c.challenge_state_id = 5) 
      OR (c.opponent_id = u.id AND c.challenge_state_id = 4)' 

    won = 'SELECT COUNT(c.id) FROM challenges AS c 
      WHERE (c.challenger_id = u.id AND c.challenge_state_id = 4) 
      OR (c.opponent_id = u.id AND c.challenge_state_id = 5)' 

    # WHERE statement prevents division by zero 
    find_by_sql(
    'SELECT u.*, cast(('+won+') as float)/(cast(('+won+') as float)+cast(('+lost+') as float)) AS win_ratio, ('+won+') AS won, ('+lost+') AS lost 
    FROM users AS u 
    WHERE ('+won+') > 0 
    ORDER BY win_ratio DESC, won DESC 
    LIMIT '+limit.to_s 
) 
end 

我正在使用此查詢排序排名表中的用戶,它工作正常。球員當前排名

現在我需要一個查詢來告訴我show view中用戶的當前排名。可能嗎?

回答

1

您可以爲查詢添加「排名」並將其用作子選擇。在周邊查詢用在哪裏得到你的用戶:

select * from 
    (select @rownum:[email protected]+1 ‘rank’, YOUR_QUERY from YOUR_TABLE, (SELECT @rownum:=0) r) e 
where user_id = 1; 

考慮緩存用戶的級別,因爲subquerys是「昂貴」(需要較長時間運行/需要多大的內存)。

1

請在嘗試之前嘗試Google,例如, 「mysql select player rank」結果如下:Fast mySQL leaderboard with player rank (& surrounding players)這幾乎可以回答你的問題。

然而,你想要做的任務是非常昂貴的。如果表格中有很多項目,我會考慮在用戶的分數發生變化時將規格歸一化並重新計入整個表格。