sql select - 另一个带NULL的select只返回NULL

时间:2012-02-03 13:16:53

标签: mysql sql

我有一个像下面的那个做另一个选择的减号。我遇到的问题是,如果第二个SELECT(减去的那个)返回NULL,即使第一个查询有值,完整查询也会返回NULL。似乎MySQL认为1-NULL = NULL。我该如何解决这个问题?

SELECT round(sum(iv.`amount`)) - 
(
 SELECT round(sum(pay.`amount`)) amountSum

     FROM invoice iv
    LEFT JOIN invoiceFactoring ivf on ivf.invoiceID=iv.invoiceID 
    LEFT JOIN user systemuser ON (systemuser.userID=iv.ownerUserID)
    LEFT JOIN Payment pay ON (pay.`invoiceID`=iv.`invoiceID`)
     WHERE 
        (iv.invoiceStateID = 2 OR iv.invoiceStateID = 3) 
     AND 
    (ivf.`invoiceFactoringProcessID` = 7)
     AND     (pay.`paymentMethodID` = 1 OR pay.`paymentMethodID` = 2)
     AND systemuser.`groupID` = 1 
     AND iv.`disabled` <> 1 
     AND ivf.`invoiceExpiryDate` BETWEEN date_add(now(), INTERVAL - 28 DAY) AND date_add(now(), INTERVAL - 21 DAY)

)
    FROM invoice iv
    LEFT JOIN invoiceFactoring ivf on ivf.invoiceID=iv.invoiceID 
        LEFT JOIN user systemuser ON (systemuser.userID=iv.ownerUserID)
    WHERE 
    (iv.invoiceStateID = 2 OR iv.invoiceStateID = 3)
        AND 
    (ivf.`invoiceFactoringProcessID` = 7 or ivf.`invoiceFactoringProcessID`)
    AND systemuser.`groupID` = 1 
    AND iv.`disabled` <> 1   /* ta bort de som är inaktiva*/    
    AND ivf.`invoiceExpiryDate` BETWEEN date_add(now(), INTERVAL - 28 DAY) AND date_add(now(), INTERVAL - 21 DAY)

3 个答案:

答案 0 :(得分:1)

也许你可以用IFNULL包装“内部”sql

SELECT round(sum(iv.`amount`)) - 
IFNULL((
 SELECT round(sum(pay.`amount`)) amountSum
 FROM invoice iv
 LEFT JOIN invoiceFactoring ivf on ivf.invoiceID=iv.invoiceID 
 LEFT JOIN user systemuser ON (systemuser.userID=iv.ownerUserID)
 LEFT JOIN Payment pay ON (pay.`invoiceID`=iv.`invoiceID`)
 WHERE 
    (iv.invoiceStateID = 2 OR iv.invoiceStateID = 3) 
 AND 
    (ivf.`invoiceFactoringProcessID` = 7)
 AND     (pay.`paymentMethodID` = 1 OR pay.`paymentMethodID` = 2)
 AND systemuser.`groupID` = 1 
 AND iv.`disabled` <> 1 
 AND ivf.`invoiceExpiryDate` BETWEEN date_add(now(), INTERVAL - 28 DAY) 
 AND date_add(now(), INTERVAL - 21 DAY)
),0)

FROM invoice iv
LEFT JOIN invoiceFactoring ivf on ivf.invoiceID=iv.invoiceID 
    LEFT JOIN user systemuser ON (systemuser.userID=iv.ownerUserID)
WHERE 
(iv.invoiceStateID = 2 OR iv.invoiceStateID = 3)
    AND 
(ivf.`invoiceFactoringProcessID` = 7 or ivf.`invoiceFactoringProcessID`)
AND systemuser.`groupID` = 1 
AND iv.`disabled` <> 1   /* ta bort de som är inaktiva*/    
AND ivf.`invoiceExpiryDate` BETWEEN date_add(now(), INTERVAL - 28 DAY) AND date_add(now(), INTERVAL - 21 DAY)

答案 1 :(得分:0)

使用null执行任何操作都将返回null。如果使用COALESCE或IFNULL为null,则需要定义要发生的内容。 请查看http://www.w3schools.com/sql/sql_isnull.asp以获取示例。

答案 2 :(得分:0)

  

似乎MySQL认为1-NULL=NULL

是;这是正确的。 “一个”减去“未知”是“未知”。如果您希望将第二个子查询的NULL视为0,则需要将其包含在the COALESCE operator的调用中:将(SELECT ...)更改为COALESCE((SELECT ...), 0)