我正在努力通過關系從多對多中獲得正確的點回傳值。我有表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但不同的陳述句似乎在組之后運行,因此它在計算程序中仍然包括重復項。
uj5u.com熱心網友回復:
也許之前嘗試選擇distinct,不要使用.distinctruby的功能。做類似的事情(Select distinct seasons FROM..)。它應該讓你沒有重復。
uj5u.com熱心網友回復:
我最終通過簡單地添加driver_teams.id到 group by 子句中解決了這個問題
season.teams.joins(:results).select('teams.*, SUM(results.points) AS points').group('teams.id, driver_teams.id')
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361364.html
標籤:sql 红宝石轨道 PostgreSQL的
