MySQL连接查询混淆

标签 mysql sql join

我有如下 3 个表:

  1. 产品(product_id,product_desc)
  2. product_sales_branch_a(product_id,数量)
  3. 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 行作为输出。这就是为什么您的总和比预期的大得多。

Sample

解决此问题的一种方法是使用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/

相关文章:

python - 如何在具有相同列名的 sqlalchemy 查询中加入不同的表?

mysql - 如何使用条件对 mysql 数据库进行不同的连接

php - 将字符串与MySQL中的字段值连接起来

MySQL 距离关系的传递闭包

mysql - 使用 count(*) 和 inner join 时查询速度慢

sql - 从列中具有相同值的 SQL Server 表中检索行

mysql - SQL查询如何选择数据即使WHERE子句中的条件不匹配

PHP 无法连接到 Live Site 上的 Sphinx

mysql - Magento EE 数据库没有触发器

sql - 如果一条记录包含特定值,如何排除整个组?