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视图中用户的当前排名。有可能吗?
答案 0 :(得分:1)
请在问之前尝试谷歌,例如“mysql select player rank”导致:Fast mySQL leaderboard with player rank (& surrounding players)几乎可以回答你的问题。
但是,您想要完成的任务非常昂贵。如果你在表格中有很多项目,我会考虑对每个用户的分数变化进行非规范化排名并重新计算整个表格。
答案 1 :(得分:1)
您可以在查询中添加“排名”,并将其用作子选择。在周围的查询中,使用从哪里获取用户:
select * from
(select @rownum:=@rownum+1 ‘rank’, YOUR_QUERY from YOUR_TABLE, (SELECT @rownum:=0) r) e
where user_id = 1;
考虑缓存用户的等级,因为subquerys“很贵”(需要很长时间才能运行/需要大量内存)。