2

所以我有一个锦标赛的结果表,其中同一个玩家可能会发生多场比赛。

所以一些样本数据可能是:

结果

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 字段,并按该计数字段分组。

所以伪代码就像......

范围 :most_wins, :all, :order_by => "Count(Player Wins)"

这甚至可能还是我应该重新考虑我的数据库结构?

4

1 回答 1

2

首先也是最重要的:命名作用域已死

我建议您执行以下操作:

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 注入。

于 2012-05-18T22:56:43.497 回答