2012-09-05 52 views
0

當我運行此查詢:MySQL的子查詢領域相減的結果不正確

select 
(IFNULL(ROUND(convertUnits('40892',SUM(o.qty),o.pricingUnit,'FT')),0)) as oItemQty, 
(SELECT IFNULL(sum(i.qty),0) from inventory i where i.partID='40892' and i.type=16 and  i.refDocNum=w.woID and i.refApp='WO') as iItemQty, 
(IFNULL(ROUND(convertUnits('40892',SUM(o.qty),o.pricingUnit,'FT')),0) - (SELECT IFNULL(sum(i.qty),0) from inventory i where i.partID='40892' and i.type=16 and i.refDocNum=w.woID and i.refApp='WO')) as sum 
from orderitem o left join wo w on o.orderitemID=w.orderitemID 
where o.partID='40892' and 
w.status not in (1,5) and 
(SELECT cancelDate from orders where orders.orderID=o.orderID)='0000-00-00' and 
o.createWO=1 and 
(SELECT orderDate from orders where orders.orderID=o.orderID) >='2012-07-01' 

我得到13650的 「oItemQty」 和2730的 「iItemQty」。我遇到的問題是字段「總和」應該是oItemQty - iItemQty(10920)。現在它正在返回13650(oItemQty)。

我在這裏失蹤了什麼?爲什麼當我運行子查詢作爲單獨的字段是數字正確的,但是當我試圖減去它不正常工作?

更新:原來,這是一個鑄造問題。一旦我將iItemQty作爲未簽名進行鑄造,就會正確扣除它。在查詢

+0

什麼是'convertUnits'? – Kermit

+0

請提供樣本數據和期望的輸出。 – RedFilter

+0

@njk convertUnits是一個存儲過程。我認爲這不是問題,如果我去 (IFNULL(ROUND(convertUnits('40892',SUM(o.qty),o.pricingUnit,'FT')),0) - 2730)as sum 我得到了正確的結果 - 所以它似乎與後者子查詢有關? – drschultz

回答

0

看,我注意到的第一個問題是,你否定你的左邊,包括這個WHERE子句中加入:

w.status not in (1,5) 

你應該移動到這左邊的ON子句加盟保持該連接的意圖。現在,它基本上被視爲內部連接。

+0

Ike - 這使情況變得更糟,在我的查詢中,因爲它是oItemQty和iItemQty都是正確的,我只是不能讓它們減去 – drschultz

+0

你應該儘可能多地替換子節點,請儘可能使用聯接進行查詢。例如,加入訂單表以通過cancelDate和orderDate進行過濾。 –