一、四者的使用
1.if(flag,value1,value2)
若是flag(可以是一个表达式)结果为真,则返回第二个参数,为假则返回第三个参数,如下:
select if(true,"真","假") as '列1',if(false,"真","假") as '列2' from dual;
2.ifnull(value1,value2)
若是value1为null则返回value2,否则返回value1,如下:
select ifnull(null,"非null") as '列1',ifnull("非null",null) as '列2' from dual;
3.case flag when
case when有两种用法,当前这种和java里的switch可以说一模一样了,举例如下:
select (case project.status when 0 then '未交付' when 1 then '滚动交付' when 2 then '已交付' END ) as 状态 from project;
4.case when flag
这种写法将判断写在when后,这种写法麻烦一些,但是相对于上面的写法则更灵活一些,可以不受字段的约束,比如:
select (case when p.STATUS = '0' then '未交付' when p.STATUS = '1' then '滚动交付' when p.STATUS = '2' then '已交付' end ) as 状态 from tb_mdm_project p;
二、典型场景
场景:version 字段可能为null,需要取值对在程序里进行运算,那么我们在获取时是要判断该值是否可能为null的情况的。
解决一:
select ifnull(p.version,0) from tb_mdm_project p;
解决二:
select if(p.version is null,0,p.version) from tb_mdm_project p ;
解决三:
select (case when p.version is null then 0 else p.version end ) as version from tb_mdm_project p ;