在mysql中使用SUM和多个连接

时间:2013-01-02 01:18:45

标签: mysql database join sum relational-database

我一直在寻找解决方案,有很多类似的问题,但没有任何正确的答案可以帮我解决问题。

首先,我的问题/问题:

  1. 我想对多个连接查询中的某些列进行求和和计算
  2. 多个连接是不可能的?我是否需要嵌套SELECT个查询?
  3. 这是我的数据库的SQL转储,包含示例数据:http://pastie.org/private/vq7qkfer5mwyraudb5dh0a

    这是我认为可以解决的问题:

    SELECT firstname, lastname, sum(goal.goal), sum(assist.assist), sum(gw.gw), sum(win.win), count(played.idplayer) 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)
    GROUP BY idplayer
    

    我想要生成的是一个表格,其中目标,辅助,gw,win和play的列是该列中每行的总和/计数,如下所示:(提供的样本数据)

    +-----------+----------+------+--------+----+-----+--------+
    | firstname | lastname | goal | assist | gw | win | played |
    +-----------+----------+------+--------+----+-----+--------+
    | Gandalf   | The White|   10 |      6 |  1 |   1 |      2 |
    | Frodo     | Baggins  |   16 |      2 |  1 |   2 |      2 |
    | Bilbo     | Baggins  |    7 |      3 |  0 |   0 |      2 |
    +-----------+----------+------+--------+----+-----+--------+
    

    那么,为了再次迭代上述问题,这可能是一个查询和多个连接吗?

    如果您提供解决方案/查询,请解释一下!我是适当的关系数据库的新手,我从未在此项目之前使用过连接。除非必要,否则我也会感谢你避免使用别名。

    我已经运行了上面的查询,没有求和和分组,我为每个列SELECT打开了一组行,我怀疑它是相乘或加在一起的,但我的印象是分组和/或执行sum(TABLE.COLUMN)可以解决这个问题。

    另一件事是,我认为,执行SELECT DISTINCT或任何其他DISTINCT操作将无效,因为这会遗漏一些(“重复”)结果。

    PS。如果重要的话,我的开发机器是一个WAMP,但是发布将在ubuntu / apache / mysql / php上。

1 个答案:

答案 0 :(得分:12)

要了解为什么没有得到您期望的答案,请查看此查询:

SELECT * FROM player LEFT JOIN goal USING (idplayer)

如您所见,左侧的行与右侧的匹配行重复。对每个连接重复该过程。这是您查询的原始数据:

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)

然后将这些重复值用于SUM计算。需要在连接行之前计算SUM:

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