首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MySQL连接查询混淆

问MySQL连接查询混淆
EN

Stack Overflow用户
提问于 2014-12-30 10:34:24
回答 2查看 67关注 0票数 1

我有3张桌子如下:

  1. 产品(product_id,product_desc)
  2. product_sales_branch_a (product_id,qty)
  3. product_sales_branch_b (product_id,qty)

我使用join product & product_sales_branch_a来获得销售数量,使用以下脚本:

代码语言:javascript
复制
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*'

结果:

代码语言:javascript
复制
product_desc | sum(B.qty)    
1234         | 16

结果正确返回。

然后,我使用join product & product_sales_branch_b来使用以下脚本获得销售数量:

代码语言:javascript
复制
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'

结果:

代码语言:javascript
复制
product_desc | sum(C.qty)
1234         | 20

结果也正确返回。

但是现在,我试图通过以下脚本加入3表:

代码语言:javascript
复制
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'

结果:

代码语言:javascript
复制
product_desc | sum(B.qty) | sum(C.qty)
1234         | 288        | 280

这不是我所期望的结果。

我的sql查询有什么问题吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-12-30 10:43:08

在这种情况下,我会选择分选:

代码语言:javascript
复制
select A.product_desc,
       (select sum(B.qty) from product_sales_branch_a B where B.product_id = A.product_id),
       (select sum(C.qty) from product_sales_branch_b C where C.product_id = A.product_id) 
from product A 
where A.product_id = 'ABC'
票数 0
EN

Stack Overflow用户

发布于 2014-12-30 10:54:03

问题是,当您加入第三个表时,第二个表和第三个表之间没有任何关系。因此,如果表1和表2的联接返回m行,而1和3的联接返回n行,则将得到m*n行作为输出。这就是为什么你的总和比预期的要大得多。

示例

解决这个问题的一种方法是使用count distinct,如果您非常确定qty没有重复值的话。但是,这在实际数据中不太可能,因此您应该考虑使用上面@jarlh建议的子查询方法:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27703837

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档