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;

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM