9

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

首先,我的问题/问题:

  1. 我想对多连接查询中的某些列进行求和和计数
  2. 多个连接不可能吗?我必须嵌套SELECT查询吗?

这是我的数据库的 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 上。

4

1 回答 1

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

于 2013-01-02T01:54:10.037 回答