2014-06-11 42 views
1

我想加入兩個查詢,希望獲得與個別查詢相同的結果。我絕不是熟練的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,我不知道如何渲染。

感謝任何人可以提供幫助!

+1

爲什麼要加入2個完全不同的查詢? –

+0

你可以在你的問題上發表你的表格結構嗎? –

+0

你正在做一個「樹」加入。 'A-> B'和'A-> C'。如果表B和C有不同的行數,你會得到不平衡的結果。 「更大」的一面會強制小方缺失的行被空值填充。 –

回答

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 
+0

有沒有辦法使第二個查詢繼承第一個查詢中的asin和sku。我詢問的原因是因爲當我完成了這個查詢(很多步驟還在繼續)時,我不會使用預定義的asin和sku,例如:「fbaoh.asin ='B002BRSCJ6'和fbaoh.sku ='643356041428'「。該查詢將運行在所有行上,然後渲染結果數組。謝謝! – LargeTuna

+0

@LargeTuna並非如此。在你的PHP代碼中,應該可以傳遞相同的值兩次。這些實際上是兩個單獨的查詢感謝聚合,所以我不知道一個乾淨的方式來使用該變量一次。 – Vulcronos