简体   繁体   中英

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:

    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)

My question is how do you make a CASE that says if null THEN 0 ELSE normal?

Check the COALESCE function. In your case you will do this:

COALESCE(normal, 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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