MySQL SUM在包含多个连接的查询中输出错误的值

时间:2012-07-22 00:00:13

标签: mysql join sum

我使用以下查询获取有关这些表的信息,但是defenderhit和defenderdamage SUM值将与第一个连接的行号的行数相乘。

表'战斗':

battle_id   city_id     attacker    defender    battle_time 
1           07          6           0           1342918014

表'战斗':

battle_id   family_id   user_id     hits    damage 
1           0           0           1000    50000
1           6           15          108     3816
1           6           2           81  2046
1           6           1           852 1344

MySQL查询

SELECT b.battle_id, b.city_id, b.attacker, b.defender, b.battle_time,
SUM(COALESCE(bh1.damage,0)) AS attackerdamage, SUM(COALESCE(bh2.damage,0)) AS defenderdamage,
SUM(COALESCE(bh1.hits,0)) AS attackerhit, SUM(COALESCE(bh2.hits,0)) AS defenderhit
FROM battles AS b
LEFT JOIN battlehits AS bh1 ON b.attacker = bh1.family_id
LEFT JOIN battlehits AS bh2 ON b.defender = bh2.family_id
WHERE b.battle_id=1
GROUP BY b.battle_id LIMIT 1

此查询的结果如下:

battle_id   city_id     attacker    defender    battle_time     attackerdamage  defenderdamage  attackerhit     defenderhit 
1           07          6           0           1342918014      7206            150000          1041            3000

正如您在表数据中看到的那样,defenderhit和defenderdamage SUM值应该是1000和50000,但它们乘以3。 我在这做什么?有什么问题?

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以使用

模拟不同行的SUM
(SUM(t.field_to_sum) / COUNT(t.primary_key) * COUNT(DISTINCT t.primary_key))

答案 1 :(得分:1)

你在组之前得到三行/ sum。对于来自战斗的三个攻击者行中的每一行,您都有一行。这些中的每一个都与来自战斗的相同防御者行配对,导致防御者数据增加三倍。要查看此内容,请删除group by和limit子句并取出sum()s。你正在有效地创造所有防御者X的所有攻击者的交叉产物,然后总结。

这显示了具有重复的防御者数据的三行。这是对一对多关系进行连接的结果,而不是一对一的关系。

SELECT b.battle_id, b.city_id, b.attacker, b.defender, b.battle_time,
COALESCE(bh1.damage,0) AS attackerdamage, COALESCE(bh2.damage,0) AS defenderdamage,
COALESCE(bh1.hits,0) AS attackerhit, COALESCE(bh2.hits,0) AS defenderhit
FROM battles AS b
LEFT JOIN battlehits AS bh1 ON b.attacker = bh1.family_id
LEFT JOIN battlehits AS bh2 ON b.defender = bh2.family_id
WHERE b.battle_id=1;

输出:

battle_id   city_id attacker    defender    battle_time attackerdamage  defenderdamage  attackerhit defenderhit
1   7   6   0   1342918014  3816    50000   108 1000
1   7   6   0   1342918014  2046    50000   81  1000
1   7   6   0   1342918014  1344    50000   852 1000

您需要将其拆分为单独的查询。一个用于攻击者总和,另一个用于防御者总和。