我有如下 3 个表:
- 产品(product_id,product_desc)
- product_sales_branch_a(product_id,数量)
- product_sales_branch_b(product_id,数量)
我使用 join product & product_sales_branch_a 通过以下脚本获取销售数量:
select A.product_desc, sum(B.qty) from product A
join product_sales_branch_a B on B.product_id = A.product_id
where A.product_id = 'ABC*'
结果:
product_desc | sum(B.qty)
1234 | 16
结果正确返回。
然后,我使用 join product & product_sales_branch_b 通过以下脚本获取销售数量:
select A.product_desc, sum(C.qty) from product A
join product_sales_branch_b C on C.product_id = A.product_id
where A.product_id = 'ABC'
结果:
product_desc | sum(C.qty)
1234 | 20
结果也正确返回。
但是现在,我正尝试通过以下脚本加入 3 表:
select A.product_desc, sum(B.qty), sum(C.qty) from product A
join product_sales_branch_a B on B.product_id = A.product_id
join product_sales_branch_b C on C.product_id = A.product_id
where A.product_id = 'ABC'
结果:
product_desc | sum(B.qty) | sum(C.qty)
1234 | 288 | 280
这不是我期望的结果。
我的 sql 查询有什么问题吗?
最佳答案
问题是当你连接第三个表时,第二个和第三个表之间没有关系。因此,如果表 1 和表 2 的连接返回 m 行,而表 1 和表 3 的连接返回 n 行,您将得到 m * n 行作为输出。这就是为什么您的总和比预期的大得多。
解决此问题的一种方法是使用count distinct
,如果您非常确定qty
没有重复值。但是,这在实际数据中不太可能,因此您应该考虑使用上面@jarlh 建议的子查询方法:
select A.product_desc as desc,
(select sum(B.qty) from product_sales_branch_a B where B.product_id = A.product_id and A.product_id = 'ABC') as bqty,
(select sum(C.qty) from product_sales_branch_b C where C.product_id = A.product_id and A.product_id = 'ABC') as cqty
from product A
关于MySQL连接查询混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27703837/