mysql 的 case when then 用法 和null 的判断

表:一个表 aa 有两个字段 id 和 sex ,第1条记录的sex 为空串 (’’) 第二条记录的sex 为空 (null)
在这里插入图片描述

  1. 用法:
      第一种: select (case 字段名 when 字段值1 then 结果 when 字段值2 then 结果2 else (默认值) end )
        举例:
        在这里插入图片描述
select id ,(case sex  when ''  then 'bbbbb'
                      when  null then 'aaaaa' 
                             else sex end  ) as sex FROM aa;

这个结果是有问题的,理想的结果第二条记录为2 aaaaa ,但是确为空,说明这个判断null 条件有问题,经过测试:判断null 要用is null
在这里插入图片描述
 第二种: select (case when 判断条件1 then 结果 when 判断条件2 then 结果2 else (默认值) end )

select id ,(case   when sex= ''  then 'bbbbb'
                      when sex is null then 'aaaaa' 
                             else sex end  ) as sex FROM aa;

猜你喜欢

转载自blog.csdn.net/pdsuxueyuan/article/details/86544834