我想加入兩個查詢,希望獲得與個別查詢相同的結果。我絕不是熟練的MySQL加入查詢,因此我的困境。這是我的查詢和他們的結果。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,我不知道如何渲染。
感謝任何人可以提供幫助!
爲什麼要加入2個完全不同的查詢? –
你可以在你的問題上發表你的表格結構嗎? –
你正在做一個「樹」加入。 'A-> B'和'A-> C'。如果表B和C有不同的行數,你會得到不平衡的結果。 「更大」的一面會強制小方缺失的行被空值填充。 –