简体   繁体   English

嵌套时的情况select = null然后是else

[英]Case when nested select = null then else

Okay so i didn't quite know what to call this post i might update the title later. 好的,所以我不知道该怎么称呼这篇文章我可能会稍后更新标题。

I have the following problem: 我有以下问题:

Say for instance you have the following calculating nested sql: 比如说你有以下计算嵌套的sql:

    CREATE 
    ALGORITHM = UNDEFINED 
    DEFINER = `root`@`localhost` 
    SQL SECURITY DEFINER
VIEW `v_user_category_stat` AS
    SELECT 
        (SELECT 
                SUM(MS.score) + (SELECT 
                            SUM(UHMS.score)
                        FROM
                            User_has_module_score UHMS
                                RIGHT OUTER JOIN
                            module M ON M.id = UHMS.module_id
                                JOIN
                            Category C ON C.id = M.category_id
                        WHERE
                            UHMS.user_id = U.id)
            FROM
                Module_score MS
                    RIGHT OUTER JOIN
                Module M ON M.id = MS.module_id
                    JOIN
                Category C ON C.id = M.category_id
            WHERE
                MS.user_id = U.id) AS total_score,
        U.id
    FROM
        User U

This gives me the wanted result which is: 这给了我想要的结果,即:

# total_score, id
NULL, '2'
NULL, '7'
NULL, '8'
NULL, '9'
NULL, '10'
NULL, '11'
NULL, '12'
NULL, '13'
'13', '14'

Now i thought to my self i want to prettyfi this by making sure that if the value is null then it should be 0 (instead of null) 现在我想我自己想要通过确保如果值为null然后它应该是0(而不是null)来实现这一点

My question is how do you make a CASE that says if null THEN 0 ELSE normal? 我的问题是你如何制作一个CASE ,表明if null THEN 0 ELSE normal?

Check the COALESCE function. 检查COALESCE功能。 In your case you will do this: 在你的情况下,你会这样做:

COALESCE(normal, 0)

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

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