简体   繁体   English

如果不为空,则返回 if 语句的值

[英]Return the value of if statement in case when it's not null

How to return the value of my expression when it's true当它为真时如何返回我的表达式的值

SELECT if(((SELECT SUM(kcal) 
from jadlospis 
WHERE data ="2022-07-18" and uzytkownik_id=1 
GROUP BY DAY(data)) as expr) IS NULL,expr,'0') 
#1064 - Something is wrong in your syntax obok 'as expr) IS NULL,expr,'0') LIMIT 0, 25' w linii 4.

How can i resolve my problem?我该如何解决我的问题?

You cannot use an alias in the IF() function.不能在IF()函数中使用别名。 Repeat the full expression instead.而是重复完整的表达式。 Besides , redundant parenthesis can be removed.此外,可以删除多余的括号。 Try this:尝试这个:

SELECT if(
    (SELECT SUM(kcal) 
    from jadlospis 
    WHERE data ="2022-07-18" and uzytkownik_id=1 
    GROUP BY DAY(data)
    ) IS NULL,  -- don't use an alias
    (SELECT SUM(kcal) 
    from jadlospis 
    WHERE data ="2022-07-18" and uzytkownik_id=1 
    GROUP BY DAY(data)
    ), -- repeat the full expression 
    '0'
        ) 
;

-- in this case, it's better to use the IFNULL(expr1,expr2) function which returns expr1 if it is not null ,otherwise returns expr2 .
SELECT ifnull(
    (SELECT SUM(kcal) 
    from jadlospis 
    WHERE data ="2022-07-18" and uzytkownik_id=1 
    GROUP BY DAY(data)
    ) ,  
    '0'
        ) 
;

According to this syntax IF(condition, true_value, false_value) , if the condition is true 'true_value' will be returned.根据此语法IF(condition, true_value, false_value) ,如果条件为真,将返回“true_value”。 In your case, 'true_value' is NULL because the expression 'expr' upon being true returns NULL as per your condition.在您的情况下,“true_value”为 NULL,因为表达式“expr”为真时根据您的条件返回 NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM