Using SUM with multiple joins in mysql

前端 未结 1 1787
情书的邮戳
情书的邮戳 2021-02-04 14:00

I\'ve been looking for a solution to this, there\'s plenty of similar questions but none have any proper answers that helped me solve the problem.

First up, my questions

相关标签:
1条回答
  • 2021-02-04 14:35

    To understand why you're not getting the answers you expect, take a look at this query:

    SELECT * FROM player LEFT JOIN goal USING (idplayer)
    

    As you can see, the rows on the left are duplicated for the matching rows on the right. That procedure is repeated for each join. Here's the raw data for your query:

    SELECT * FROM player
    LEFT JOIN goal USING (idplayer)
    LEFT JOIN assist USING (idplayer)
    LEFT JOIN gw USING (idplayer)
    LEFT JOIN win USING (idplayer)
    LEFT JOIN played USING (idplayer)
    

    Those repeated values are then used for the SUM calculations. The SUMs need to be calculated before the rows are joined:

    SELECT firstname, lastname, goals, assists, gws, wins, games_played
    FROM player
    INNER JOIN 
      (SELECT idplayer, SUM(goal) AS goals FROM goal GROUP BY idplayer) a
      USING (idplayer)
    INNER JOIN
      (SELECT idplayer, SUM(assist) AS assists FROM assist GROUP BY idplayer) b
      USING (idplayer)
    INNER JOIN
      (SELECT idplayer, SUM(gw) AS gws FROM gw GROUP BY idplayer) c
      USING (idplayer)
    INNER JOIN
      (SELECT idplayer, SUM(win) AS wins FROM win GROUP BY idplayer) d
      USING (idplayer)
    INNER JOIN
      (SELECT idplayer, COUNT(*) AS games_played FROM played GROUP BY idplayer) e
      USING (idplayer)
    

    SQLFiddle

    0 讨论(0)
提交回复
热议问题