MySQL学习笔记:流程控制函数if、case用法

/*
5、流程控制函数
if(expr1,a,b)  # 如果expr1为true,结果返回a,否则返回b
case()
*/

-- select if (10<5,'大','小');
# if
# 查询是否有奖金
-- use myemployees;
-- select last_name,commission_pct,if(commission_pct is not null,'有奖金','无奖金') as ps from employees;
-- select last_name,commission_pct,if(commission_pct,'有奖金','无奖金') as ps from employees;   # 等同于上列语句
-- 
/*
case: 功能1:switch case效果:常用于处理等值判断
语法:
case 表达式/字段
when 常量1 then 要显示的值1或者语句1(与select联合使用不能用语句);
when 常量2 then 要显示的值2或者语句2(与select联合使用不能用语句);
...
else 要显示的值n或者语句n;
end

备注: 从case开始到end结束相当于一个表达式,可以起别名,然后与select联合使用
*/

/* 案例
查询员工的工资,
如果部门号为30,显示工资为1.1倍;
如果部门号为40,显示工资为1.2倍;
如果部门号为50,显示工资为1.3倍;
其他,原工资;
*/
select department_id,salary,    # 注意salary后面的,不能少
(case department_id       # 加()是为了体现case...end可以看作一个表达式,不加()也可以
when 30 then salary*1.1   # then后面是值,不需要加;
when 40 then salary*1.2
when 50 then salary*1.3
else salary
end) as 新工资 
from employees;


/*
case: 功能2:多重if : 区间判断
语法:
case
when 条件1 then 值1或语句1; #语句才加;
when 条件2 then 值2或语句2; 
when 条件3 then 值3或语句3; 
else 要显示的值n或语句n; 
end

备注: 从case开始到end结束相当于一个表达式,可以起别名,然后与select联合使用
*/

/* 案例:
查询员工的工资情况
如果工资>20000;显示A级别;
如果工资>15000;显示B级别;
如果工资>10000;显示C级别;
其他,显示D级别;
*/
select last_name,salary,
case 
when salary>20000 then 'A'
when salary>15000 then 'B'
when salary>10000 then 'C'
else 'D'
end as 工资级别
from employees;

原文地址:https://www.cnblogs.com/feynmania/p/14785756.html