我创建了一个查询,当从子查询返回null时我想返回0,我使用了IFNULL函数,但最后我仍然得到null。下面是一个类似的查询,请帮忙,不知道该怎么做。 (PS:我用手机写这个,所以mu形成可能看起来很糟糕,抱歉)
SELECT t1.id, t1.Amount, t1.parent,
( SELECT @Total := IFNULL(SUM(t2.amount), 0) AS amount FROM transactions t2 WHERE t1.`id` = t2.parent GROUP BY t2.parent ) AS AmountRepaid,
( SELECT CASE WHEN CAST(SUM(t3.amount) AS DECIMAL) > CAST(t1.amount AS DECIMAL) THEN "Over" WHEN CAST(SUM(t3.amount) AS DECIMAL) = CAST(t1.amount AS DECIMAL) THEN "Complete" ELSE "Incomplete" END FROM transactions t3 WHERE t1.`id` = t3.Parent GROUP BY t3.Parent ) AS PaymentStatus
FROM transactions t1 WHERE t1.`Parent` IS NULL;
答案 0 :(得分:4)
尝试使用以下方式:
SELECT t1.id, t1.Amount, t1.parent,
@Total := IFNULL( ( SELECT SUM(t2.amount) AS amount FROM transactions t2 WHERE t1.`id` = t2.parent GROUP BY t2.parent ), 0) AS AmountRepaid,
答案 1 :(得分:1)
试试这个:
SELECT t1.id, t1.Amount, t1.parent,
IF(SUM(t2.amount) IS NULL, 0 ,SUM(t2.amount)) AS amount FROM transactions t2 WHERE t1.`id` = t2.parent GROUP BY t2.parent ) AS AmountRepaid,
( SELECT CASE WHEN CAST(SUM(t3.amount) AS DECIMAL) > CAST(t1.amount AS DECIMAL) THEN "Over" WHEN CAST(SUM(t3.amount) AS DECIMAL) = CAST(t1.amount AS DECIMAL) THEN "Complete" ELSE "Incomplete" END FROM transactions t3 WHERE t1.`id` = t3.Parent GROUP BY t3.Parent ) AS PaymentStatus
FROM transactions t1 WHERE t1.`Parent` IS NULL;