case [expr] when [val1] then [res1]… else [default] end
如果expr的等于val1,返回res1,…否则返回default默认值
-- 流程控制函数-- ifselectif(true,'yes','no');-- ifnullselect ifnull(null,2);select ifnull(1,null);-- case-- 需求:查employee表的员工姓名和工作地址(北京/上海---->一线城市,其他---->二线城市)select name,(case workaddress when'北京'then'一线城市'when'上海'then'一线城市'else'小破地儿'end)as'工作地址'from employee ;createtable score(
id intcomment'ID',
name varchar(20)comment'姓名',
math intcomment'数学',
english intcomment'英语',
chinese intcomment'语文')comment'学员成绩表';insertinto score(id, name, math, english, chinese)VALUES(1,'Tom',67,88,95),(2,'Rose',23,66,90),(3,'Jack',56,98,76);-- 案例:统计班级各个学员的成绩,展示的规则如下-- >= 85,展示优秀-- >= 60,展示及格-- 否则,显示不及格select id,
name,(casewhen math >=85then'优秀'when math >=60then'及格'else'不及格'end)as'数学',(casewhen english >=85then'优秀'when english >=60then'及格'else'不及格'end)as'英语',(casewhen chinese >=85then'优秀'when chinese >=60then'及格'else'不及格'end)as'语文'from score;