【发布时间】:2014-06-11 17:05:08
【问题描述】:
我正在尝试加入两个查询,希望获得与单个查询相同的结果。我绝不擅长 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
亚马逊物流库存
id | sku | asin | fbaInventoryReport_id
---------------------------------------------------
1 | ABC | 123 | 1
亚马逊物流库存报告
id | report_datetime
---------------------------------------------------
1 | 2014-05-20 06:06:03
查询 #1 - 我根据 sku 和 asin 以及日期范围得到总和。
查询 #2 - 我根据 sku 和 asin 以及日期范围获取总行数。
查询 #3 - 我想要得到相同的结果。两个查询之间的唯一联系是 sku 和 asin。
很明显,上次查询的结果不是我想要收到的。我究竟做错了什么?
这是我能说的。该查询不仅向我显示 sumQty 和 totalRows,而是将 sumQty (139) 和 totalRows (30) 相乘,因此等于:4170。至于 3840,我不知道这是如何呈现的。
感谢任何人都可以为我提供的任何帮助!
【问题讨论】:
-
为什么要加入两个完全不同的查询?
-
你能在你的问题上发布你的表格结构吗?
-
你正在做一个“树”连接。
A->B和A->C。如果表 B 和 C 的行数不同,您将得到不平衡的结果。 “较大”一侧将强制较小一侧的缺失行用空值填充。 -
查询不是不言自明的。我们不知道这三个表中有什么,也不知道它们作为一个整体是如何关联的。
-
我正在添加表架构。