【问题标题】:Get win-loss for each team in Teams table using Games table?使用 Games 表获取 Teams 表中每个团队的胜负?
【发布时间】:2012-05-09 18:03:59
【问题描述】:

我正在创建一个使用 RoR 来管理篮球联赛的应用。我有两张桌子:Teams & GamesGames 表使用外键接受两个团队,并包含每个团队的得分量,如下所示:

现在,我想列出所有球队,然后是他们的输赢记录。我想不出一个更简单的方法来做到这一点,而不是一个 foreach 循环来计算包含该团队的游戏表中的所有记录,并且该团队比其他团队拥有更多。然后又是损失。必须有更简单的方法。

有什么建议吗?

【问题讨论】:

    标签: ruby-on-rails database-design application-design


    【解决方案1】:

    我同意最好不要在 Ruby 中加载所有记录并计算这些记录。在 SQL 查询中执行此操作会快得多。

    def team_stats(team_id)
      # Wins are any game where the team played and scored higher than the other team
      wins = Game.where('(home_team_id = ? AND home_team_score > away_team_score) OR (away_team_id = ? AND home_team_score < away_team_score)', team_id, team_id).count
    
      # The opposite for losses
      losses = Game.where('(home_team_id = ? AND home_team_score < away_team_score) OR (away_team_id = ? AND home_team_score > away_team_score)', team_id, team_id).count
    
      # Ties are not accounted for
    
      return {:wins => wins, :losses => losses}
    end
    

    【讨论】:

    • 喜欢它,我不知道为什么我没有想到这一点。继续发布,接下来我要为每场比赛的每位球员添加统计数据!
    • 祝你好运 :) 我编辑了几次,所以请确保您看到的是最新版本。
    猜你喜欢
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 2021-05-22
    • 2021-03-20
    • 1970-01-01
    相关资源
    最近更新 更多