1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| -- 判断正确 select if(true,'ok','error'); -- 输出 ok
-- 判断为空 select ifnull('ok','default'); -- 输出 ok select ifnull('','default'); -- 输出 ’‘ select ifnull(null,'default'); -- 输出 default
-- case 字段名 when 条件 then 结果 (可写多个when then.)else 其他 end (结束) -- 需求1: 查询employee表的员工姓名和工作地址 select -- 更类似于C语言中 SWITCH CASE 语法 name , (case workno when '北京' then '一线城市' when 'shanghai' then '二线城市' else '三线城市' end ) as '工作地址' from employee ; -- 输出 全是三线哈哈哈哈 -- 需求2: 查询employee表年龄age大于1的人 select -- 更类似与 C语言中if else 语法 name , (case when age >= 1 then '三岁儿童' else '未出生婴儿' end) from employee; -- ----------------------------------------------------------------------------------- -- 案例:统计班级各个学院的成绩(大于等于八十为优秀,大于等于六十为及格,其他为不及格) -- 案例准备 create table score ( id int comment 'ID', name varchar(20) comment '姓名', math int comment '数学', english int comment '英语', chinese int comment '语文' )comment '学院成绩表'; -- 创建表结构
insert into score (id, name, math, english, chinese) VALUES (1,'Tom',67,88,95),(2,'Rose',23,66,90),(3,'Jack',56,98,76); -- 插入成绩
select id, name, (case when math >= 80 then '优秀' when math >= 60 then '及格' else '不及格' end ) as '数学成绩', (case when english >= 80 then '优秀' when english >= 60 then '及格' else '不及格' end ) as '英语成绩', (case when chinese >= 80 then '优秀' when chinese >= 60 then '及格' else '不及格' end ) as '语文成绩' from score ; -- 输出一个表格反正
|