MySQL数据库如果SQL语句中的字段为null时则使用0代替

1.背景

在书写查询的SQL语句时,如果字段为null时,要使用0代替.

2.解决方案

CASE WHEN 字段 IS NOT NULL THEN 值 ELSE 0 END
或者
ifnull(字段,0) as 别名(可以省略as)

3.示例

ifnull(字段,0) as 别名(可以省略as)


    SELECT pdme.tuid,pdme.role_id,pupv.nickname,pupv.photo_link,pdm.member_role,pdme.status,(IFNULL(pdmam.tuid,0)) armyTuid
    FROM pm_donation_match_enroll pdme 
    LEFT JOIN pm_donation_member pdm
    ON (pdme.donation_id = pdm.donation_id
    AND pdme.role_id = pdm.member_id)
    LEFT JOIN pm_user_profile_view pupv
    ON pdme.role_id = pupv.role_id
		LEFT JOIN pm_donation_match_army_member pdmam
		ON pdme.role_id = pdmam.play_id
    WHERE
    pdme.donation_id = 221 
    AND pdme.donation_match_id = 686
    AND pdme.status IN (1,2)
    AND pdm.delete_flag = 0

CASE WHEN 字段 IS NOT NULL THEN 值 ELSE 0 END


    SELECT pdme.tuid,pdme.role_id,pupv.nickname,pupv.photo_link,pdm.member_role,pdme.status,(CASE WHEN pdmam.tuid IS NOT NULL THEN pdmam.tuid ELSE 0 END) armyTuid
    FROM pm_donation_match_enroll pdme 
    LEFT JOIN pm_donation_member pdm
    ON (pdme.donation_id = pdm.donation_id
    AND pdme.role_id = pdm.member_id)
    LEFT JOIN pm_user_profile_view pupv
    ON pdme.role_id = pupv.role_id
		LEFT JOIN pm_donation_match_army_member pdmam
		ON pdme.role_id = pdmam.play_id
    WHERE
    pdme.donation_id = 221 
    AND pdme.donation_match_id = 686 
    AND pdme.status IN (1,2) 
    AND pdm.delete_flag = 0 

4.完美解决

小伙伴们,如果你有更好的方法请给我留言哦!

你可能感兴趣的:(MySQL随笔)