LEFT JOIN如何返回值虽然主记录为空?

时间:2014-09-29 13:22:56

标签: mysql

我的SQL查询就像:

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

<{>} totalNULL不是orderID 10时,它将返回sTax值。如果<{>} totalNULLorderID 10,则sTaxNULL

如果sTaxtotal,我该如何获得NULL

1 个答案:

答案 0 :(得分: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)。

希望这会有所帮助。