MySQL加入两个表会产生不正确的结果

时间:2014-06-11 17:05:09

标签: php mysql sql join

我正在尝试加入两个查询,希望得到与单个查询一样的结果。我绝不擅长MySQL加入查询,因此我的困境。以下是我的疑问及其结果。

以下是查询#1:

select      sum(fbaoh.qty) as sumQty 
from        FBAOrderHistory fbaoh 
where       fbaoh.asin = 'B002BRSCJ6'
and         fbaoh.sku = '643356041428'
    and         fbaoh.account_id = 8
and         fbaoh.datetimePlaced BETWEEN '2014-05-12' AND '2014-06-11';
/*
sumQty = 139
*/

以下是查询#2:

select      count(fbai.id) as totalRows
from        FBAInventory fbai 
LEFT JOIN       FBAInventoryReport fbair
ON          fbai.fbaInventoryReport_id = fbair.id
where       fbai.asin = 'B002BRSCJ6'
and     fbai.sku = '643356041428'
    and         fbai.account_id = 8         
and         fbair.report_datetime BETWEEN '2014-05-12' AND '2014-06-11';
/*
totalRows = 30
*/

查询#3 - 以下是我的查询连接在一起:

select      sum(fbaoh.qty) as sumQty, 
            count(fbai.id) as totalRows
from        FBAOrderHistory fbaoh 
LEFT JOIN   FBAInventory fbai
 ON         fbaoh.asin=fbai.asin
LEFT JOIN   FBAInventoryReport fbair
 ON             fbai.FBAInventoryReport_id=fbair.id
where       fbaoh.asin = 'B002BRSCJ6'
and         fbaoh.sku = '643356041428'
    and         fbai.account_id = 8
and         fbaoh.account_id = 8        
and         fbaoh.datetimePlaced BETWEEN '2014-05-12' AND '2014-06-11'
and         fbair.report_datetime BETWEEN '2014-05-12' AND '2014-06-11';
/*
sumQty = 4170
totalRows = 3840
*/

以下是表格模式:

FBAOrderHistory

 id | qty | sku     | asin    | datetimePlaced
 ------------------------------
 1  | 1   | ABC     | 123     | 2014-05-20 06:06:03

FBAInventory

 id | sku     | asin    | fbaInventoryReport_id
 ---------------------------------------------------
 1  | ABC     | 123     | 1

FBAInventoryReport

 id | report_datetime
 ---------------------------------------------------
 1  | 2014-05-20 06:06:03

查询#1 - 我根据sku和asin以及日期范围得到总和。

查询#2 - 我根据sku和asin以及日期范围获取总行数。

查询#3 - 我希望获得相同的结果。两个查询之间唯一的连接是sku和asin。

显然,上次查询的结果并非我打算收到的结果。我究竟做错了什么?

这是我能说的。查询实际上将sumQty(139)和totalRows(30)相乘,因此等于:4170.而不是仅向我显示sumQty和totalRows,而对于3840,我不知道如何渲染它。

感谢任何人都可以提供的任何帮助!

1 个答案:

答案 0 :(得分:0)

这些查询无法加入,因为它们会在您发现时丢弃总和并计算。原因是这些表之间没有一对一的关系。最好的方法是按如下方式加入结果:

select q1.sumQty, q2.totalRows
from(
select      sum(fbaoh.qty) as sumQty 
from        FBAOrderHistory fbaoh 
where       fbaoh.asin = 'B002BRSCJ6'
and         fbaoh.sku = '643356041428'
    and         fbaoh.account_id = 8
and         fbaoh.datetimePlaced BETWEEN '2014-05-12' AND '2014-06-11') q1,
(select      count(fbai.id) as totalRows
from        FBAInventory fbai 
LEFT JOIN       FBAInventoryReport fbair
ON          fbai.fbaInventoryReport_id = fbair.id
where       fbai.asin = 'B002BRSCJ6'
and     fbai.sku = '643356041428'
    and         fbai.account_id = 8         
and         fbair.report_datetime BETWEEN '2014-05-12' AND '2014-06-11') q2