简体   繁体   中英

MySQL: Multiple joins and their effect on sums

I'm attempting to join multiple tables and use the SUM command, and I can't quite get SUM to work correctly when I join more than one table. From the reading I've done (here and elsewhere) on the topic, I'm fairly certain the solution is to sum before I join, but I'm struggling to get that done.

If I run the following code, joining only two tables, it works perfectly:

SELECT CONCAT(m.nameFirst, " ",m.nameLast) AS Name, sum(b.g) AS G,sum(b.ab) AS AB, sum(b.h) AS H, sum(b.hr) AS HR, sum(b.sb) AS SB, sum(b.bb) AS BB, ROUND(sum(b.h)/sum(b.ab), 3) AS BA, ROUND((sum(b.h)+sum(b.bb)+sum(b.hbp))/(sum(b.ab)+sum(b.bb)+sum(b.hbp)+sum(b.sf)), 3) AS OBP, ROUND((sum(b.h)+sum(b.2b)+2*sum(b.3b)+3*sum(b.hr))/sum(b.ab), 3) as SLG
FROM Master m
JOIN Batting b on m.playerID = b.playerID
WHERE birthMonth = 6 and birthDay = 15
Group by b.playerID
ORDER by b.h DESC

If I do this, adding a third table to the join, it breaks the sums:

SELECT CONCAT(m.nameFirst, " ",m.nameLast) AS Name, sum(b.g) AS G,sum(b.ab) AS AB, 
[exact same code as above removed for the sake of brevity]
sum(p.W) as WINS
FROM Master m
left JOIN Batting b on m.playerID = b.playerID
left join Pitching p on m.playerID = p.playerID
WHERE birthMonth = 6 and birthDay = 15
Group by m.playerID
ORDER by b.h DESC

As I said, I'm fairly sure the solution is to sum prior to the joins. How would I go about doing that?

Thanks in advance.

One technique is to summarize the tables, then JOIN on those tables.

SELECT CONCAT(m.nameFirst, " ",m.nameLast) AS Name
    , b.G AS G, b.AB AS AB
    , p.W as WINS
FROM Master m
LEFT JOIN 
  (SELECT playerID, SUM(g) AS G, SUM(ab) AS AB
   FROM Batting
   GROUP BY playerID) AS b
    ON m.playerID = b.playerID
LEFT JOIN 
   (SELECT playerID, sum(W) AS WINS
    FROM Pitching
    GROUP BY playerID) AS p 
  ON m.playerID = p.playerID
WHERE birthMonth = 6 and birthDay = 15

You could always move the subqueries into the SELECT structure

SELECT CONCAT(m.nameFirst, " ",m.nameLast) AS Name
    , (SELECT SUM(g)
       FROM Batting AS b
       WHERE m.playerID = b.playerID) AS G
    , (SELECT SUM(ab)
       FROM Batting
       WHERE m.playerID = b.playerID) AS AB
    , (SELECT sum(W)
       FROM Pitching AS p
       WHERE m.playerID = p.playerID) AS WINS
FROM Master m
WHERE birthMonth = 6 and birthDay = 15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM