[英]How to return zero instead of null from a subquery when a condition is not met
[英]how to return zero instead of null from a subquery in mysql
我創建了一個查詢,當從子查詢返回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;
嘗試使用以下方式:
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,
嘗試這個:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.