MySQL除以2个子查询的值

时间:2017-10-25 21:55:49

标签: mysql sql join group-by

表结构如下:

Players (PlayerID, FirstName, LastName, PositionID)
Salaries (SalaryID, PlayerID, Amount)
ScoredGoals (GoalId, PlayerID, GameID, Minute)
Positions (PositionID, PositionName)

我需要找到每个位置每个目标支付的工资。此查询产生了正确的结果,但我想知道是否有更有效的方法来执行此操作。任何帮助表示赞赏!

SELECT g.PositionName, 
(s.AvgSalPerPosition / g.GoalsPerPosition) as SalPerGoalPerPosition
FROM
    (#TOTAL GOALS PER POSITION
    SELECT po.PositionName, 
    po.PositionID,
    COUNT(GoalID) as GoalsPerPosition
    FROM ScoredGoals sg
    JOIN Players p ON sg.PlayerID = p.PlayerID 
    JOIN Positions po ON p.PositionID = po.PositionID
    GROUP BY po.PositionID) g
JOIN
    (#AVG SALARY PER POSITION
    SELECT po.PositionID, 
    AVG(Amount) as AvgSalPerPosition
    FROM Positions po
    JOIN Players p ON po.PositionID = p.PositionID
    JOIN Salaries s ON p.PlayerID = s.PlayerID
    GROUP BY po.PositionID) s ON g.PositionID = s.PositionID

1 个答案:

答案 0 :(得分:0)

通过将第二个子查询与第​​一个子查询中的表连接起来,可以只使用一个子查询而不是2来实现。

SELECT po.positionName, s.avgSalPerPosition/COUNT(*) AS salPerGoalPerPosition
FROM ScoredGoals sg
JOIN Players p ON sg.PlayerID = p.PlayerID 
JOIN Positions po ON p.PositionID = po.PositionID
JOIN (
    SELECT po.PositionID, 
        AVG(Amount) as AvgSalPerPosition
    FROM Positions po
    JOIN Players p ON po.PositionID = p.PositionID
    JOIN Salaries s ON p.PlayerID = s.PlayerID
    GROUP BY po.PositionID) s 
ON po.PositionID = s.PositionID
GROUP BY po.PositionID

但是,我怀疑你的版本会表现更好,因为聚合后加入意味着最终的连接会更小 - 它只是两个派生表,其大小是不同位置的数量。