2015-04-26 217 views
0

我試圖顯示'NULL'值爲0使用'IFNULL',但它返回所有行爲null或0.一切正常,直到我添加'lounge2'表和'lounge2order2'表。 order2.lounge2orderid是'NULL'。我知道這與'JOINS'有關,但不確定在哪裏或哪些實施。MYSQL數據庫IFNULL查詢

謝謝大家......所有的

SELECT orders2.orderid, orders2.orderdate, branch2.branchname, COUNT(orders2.garment2orderid) AS 'no gar orders', SUM(garment2.hireprice) as 'total gar sold', 
COUNT(orders2.lounge2orderid+IFNULL(orders2.lounge2orderid,0)) as 'No of lounge sales', SUM(lounge2.hirerate) 

from orders2, branch2, garment2, garment2order2, lounge2, lounge2order2 

WHERE orders2.orderid IN 

      (SELECT orders2.orderid FROM orders2 
       WHERE orders2.branchid = 2 
       AND YEAR(orders2.orderdate)= 2011) 

AND branch2.branchid IN 

      (SELECT branch2.branchid from branch2 
        WHERE branch2.branchid = orders2.branchid) 

AND garment2order2.garment2orderid IN 
      (SELECT garment2order2.garment2orderid FROM garment2order2 
       WHERE garment2order2.garment2orderid = orders2.garment2orderid) 

AND garment2.garmentid IN 

      (SELECT garment2.garmentid FROM garment2 
       WHERE garment2.garmentid = garment2order2.garmentid) 

AND lounge2order2.lounge2orderid IN 
      (SELECT lounge2order2.lounge2orderid FROM lounge2order2 
       WHERE lounge2order2.lounge2orderid = orders2.lounge2orderid) 

AND lounge2.loungeid IN 

      (SELECT lounge2.loungeid FROM lounge2 
       WHERE lounge2.loungeid = lounge2order2.loungeid)      
+0

不知道爲什麼它已經分裂了一切 – DangerousTreacle

回答

1

首先,儘量避免FROM orders2, branch2, garment2, garment2order2, lounge2, lounge2order2它必須是JOIN ... ON聲明。這將有助於您進行調試,並幫助我們理解您的邏輯和表關係。

並且要有SUMCOUNT的任何agregate功能,您應該設置GROUP BY聲明。

因爲我不知道你的數據庫結構是什麼樣的。

這裏是我的嘗試:如果你有

SELECT 
    orders2.orderid, 
    orders2.orderdate, 
    COUNT(orders2.garment2orderid) AS 'no gar orders', 
    branch2.branchname, 
    SUM(garment2.hireprice) as 'total gar sold', 
    SUM(IF(orders2.lounge2orderid IS NULL,1,0)) as 'No of lounge sales', 
    SUM(lounge2.hirerate) 
FROM orders2 
LEFT JOIN branch2 
ON branch2.branchid = orders2.branchid 
LEFT JOIN garment2order2 
ON garment2order2.garment2orderid = orders2.garment2orderid 
LEFT JOIN garment2 
ON garment2.garmentid = garment2order2.garmentid 
LEFT JOIN lounge2order2 
ON lounge2order2.lounge2orderid = orders2.lounge2orderid 
LEFT JOIN lounge2 
ON lounge2.loungeid = lounge2order2.loungeid)  
WHERE orders2.branchid = 2 
    AND YEAR(orders2.orderdate)= 2011 
GROUP BY orders2.orderid 
+0

這工作非常出色非常感謝你 – DangerousTreacle

+0

@BrianForbes你可能要仔細檢查計數/概括你得到既有休息室訂單又有服裝訂單的訂單。連接可能會導致您在結果中出現重複行,這會導致您的聚合(SUM/COUNT)數字處於關閉狀態。一個簡單的方法來檢查將只是做一個SELECT *並在最後刪除GROUP BY,然後你可以看到實際獲得聚合的數據。 –

+0

我會檢查謝謝你... – DangerousTreacle