所以我有一个锦标赛的结果表,其中同一玩家可能会发生多场比赛。
所以一些示例数据可能是:
结果
Player_ID | Match_ID|Win|Elapsed_Time|etc..
1 | 1 |T | 1:00 |etc..
2 | 1 |F | 1:00 |etc..
1 | 2 |T | 3:00 |etc..
3 | 2 |F | 3:00 |etc..
我想准备一个范围,对每个玩家设置为 True 的 Win 字段进行计数,并按该计数字段进行分组。
所以伪代码会是这样的......
scope :most_wins, :all, :order_by => “计数(玩家获胜)”
这是否可能,或者我应该重新考虑我的数据库结构?
最佳答案
首先也是最重要的:Named Scopes Are Dead
我建议您执行以下操作:
class Players < ActiveRecord::Base
....
def self.with_win_count
#inner join if you want to filter out those who doesn't have any match, otherwise is should be left outer
joins("inner join (select Player_ID, count(Match_ID) as win_count from Results where Win = true group by Player_ID) t on (t.Player_ID = Player.ID)")
end
end
#somewhere in controller you would do
best_players = Player.with_win_count.where("win_count > ?", [10]).order("win_count DESC")
如果您希望它出现在结果表中:
class Results < ActiveRecord::Base
....
def self.with_win_count
joins("inner join (select Player_ID, count(Match_ID) as win_count from Results where Win = true group by Player_ID) t on (t.Player_ID = Results.Player_ID)")
end
end
这会起作用,但我发现它有点难看。
如果您想在嵌套查询中进行条件计数,简单的方法是:
class Players < ActiveRecord::Base
....
def self.with_match_count(conditions)
#inner join if you want to filter out those who doesn't have any match, otherwise is should be left outer
joins("inner join (select Player_ID, count(Match_ID) as match_count from Results where #{conditions} group by Player_ID) t on (t.Player_ID = Player.ID)")
end
end
some_players = Player.with_match_count("Win = true").where("match_count > ?", [10]).order("match_count DESC")
!!! 请注意,如果 conditions
参数直接由用户输入构建,则很容易发生 SQL 注入(inject)。
关于ruby-on-rails-3 - Rails 3 按自累积计数对范围进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10660285/