2014-09-29 101 views
0

我的SQL查詢是這樣的:儘管主記錄爲空,LEFT JOIN應該如何返回值?

SELECT SUM(i.itemPrice) as total, t.sTax 
FROM items AS i 
LEFT JOIN tax_table AS t ON t.branchID = 10 
WHERE i.orderID = 10 

totalNULLorderID 10將返回sTax價值。如果totalNULL對於orderID 10sTaxNULL

如何獲得sTax雖然如果totalNULL

回答

1

這裏查詢你正在尋找:

SELECT SUM(i.itemPrice) AS total 
    ,CASE 
     WHEN SUM(i.itemPrice) IS NULL THEN (SELECT t.sTax 
              FROM tax_table AS t 
              WHERE t.branchID = 10 
              LIMIT 1) 
     ELSE NULL 
     END AS tax 
FROM items AS i 
WHERE i.orderID = 10 
GROUP BY i.orderID 

查詢返回的每個項目的總價格,如果這個總數NULL,返回稅(否則稅是NULL)。

希望這會有所幫助。

相關問題