[英]Inaccurate results with MySql query
I have 2 tables (import_size,export_size) both contain these 2 columns (size_id,weight) now I'm trying to get the sum of weights for each size in each table, my query looks like this 我有2个表(import_size,export_size)都包含这2列(size_id,weight),现在我想获取每个表中每个大小的权重之和,我的查询如下
SELECT sum(i.weight) imports,sum(e.weight) exports,s.size
FROM size s
LEFT JOIN import_size i on s.id=i.size_id
LEFT JOIN export_size e on s.id=e.size_id
GROUP BY s.size
now say for example in the import_size table for size 1 we have only one record but for the same size in export_size table we have 2 records, the sum of weights resulting from import_size is multiplied by 2, any thoughts? 现在说,例如,在import_size表中,对于大小1,我们只有一条记录,但是对于export_size表中的相同大小,我们有2条记录,import_size产生的权重总和乘以2,有什么想法吗?
for example: 例如:
import table has 1 record: 导入表有1条记录:
size_id 1 - weight 2
export table has 2 records: 导出表有2条记录:
size_id 1 - weight 2
size_id 1 - weight 3
the query result: 查询结果:
imports 4 - exports 5 - size 1
however it should be 但是应该
imports 2 - exports 5 - size 1
Generally speaking, a join creates a row for each permutation that match the conditions. 一般来说,联接为符合条件的每个排列创建一行。 You are joining 3 tables.
您正在加入3张桌子。 You are saying that for size 1, these tables have:
您说的是对于大小1,这些表具有:
size
: 1 row size
:1行 import_size
: 1 row import_size
:1行 export_size
: 2 rows export_size
:2行 This gives us 1*1*2=2 permutations, which means we get 2 rows. 这给我们1 * 1 * 2 = 2个排列,这意味着我们得到2行。 Obviously each contains a different
export_size
record, but what about size
and import_size
? 显然每个包含一个不同的
export_size
记录,但是size
和import_size
呢? The two rows use the same record from both of them. 两行使用来自两者的相同记录。 That means that
import_size.weight
appears twice - and that's why it's summed twice. 这意味着
import_size.weight
出现两次 -这就是为什么将其相加两次的原因。
BTW - if both tables had 2 entries for size 1, you'd get 4 permutations and both import and export sizes will be doubled. 顺便说一句-如果两个表都有2个大小为1的条目,您将得到4个排列,并且导入和导出大小都将加倍。
The solution: do the aggregation separately for each table and then do the join(not tested): 解决方案:对每个表分别进行聚合,然后进行联接(未测试):
SELECT i.imports, e.exports, s.size
FROM size AS s
LEFT JOIN (SELECT size_id,sum(weight) AS imports FROM import_size GROUP BY size_id) AS i ON s.id=i.size_id
LEFT JOIN (SELECT size_id,sum(weight) AS exports FROM export_size GROUP BY size_id) AS e ON s.id=e.size_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.