When i run this query:
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'
i get 13650 for “oItemQty” and 2730 for “iItemQty”. The problem i’m having is the field “sum” should be oItemQty – iItemQty (10920). Right now it is returning 13650 (oItemQty).
What am i missing here? Why when i run the subqueries as separate fields are the numbers correct but when i try to subtract it doesn’t work properly?
Update: Turns out it was a casting issue. Once i casted the iItemQty as unsigned it subtracted properly.
Looking at your query, the first problem I notice is that you are negating your left join by including this in the WHERE clause:
You should move that into the ON clause of the left join to preserver the intent of that join. As it is now that is essentially being treated as an inner join.