【发布时间】:2021-12-26 20:17:27
【问题描述】:
我正在努力通过关系从多对多获得正确的点返回值。我有表seasons、teams、drivers、results 和driver_teams,关系如下
class Season < ApplicationRecord
has_many :driver_teams
has_many :drivers, through: :driver_teams
has_many :teams, through: :driver_teams
end
class DriverTeam < ApplicationRecord
belongs_to :season
belongs_to :driver
belongs_to :team
has_many :results
end
class Team < ApplicationRecord
has_many :driver_teams
has_many :results, through: :driver_teams
end
class Driver < ApplicationRecord
has_many :driver_teams
has_many :results, through: :driver_teams
end
class Result < ApplicationRecord
belongs_to :driver_team
has_one :driver, though: :driver_team
has_one :team, though: :driver_team
end
results 表有一个 points 属性,它只是一个简单的整数字段
我正在尝试在如下所示的一个赛季中获得每个团队的所有积分总和
season.teams.joins(:results).select('teams.*, SUM(results.points) AS points').group('teams.id')
但是,由于使用Driverteam 直通表,一个车队可以有多个车手,这些点与每个车队的车手数重复,因为从一个赛季引用teams 将返回直通表中的多个车队。
理想的结果是让season.teams 在一个赛季中只返回每支球队的单个实例。
有没有办法防止 season.teams 在运行聚合 SQL 函数之前返回团队的副本?
我试过简单地使用season.teams.distinct,但不同的语句似乎在 group by 之后运行,因此它在计算期间仍然包括重复项。
【问题讨论】:
标签: sql ruby-on-rails postgresql