mysql> select trim(' Hello MySQL '); +-----------------------+ | trim(' Hello MySQL ') | +-----------------------+ | Hello MySQL | +-----------------------+ 1 row in set (0.00 sec)
G. substring : 截取子字符串
1 2 3 4 5 6 7
mysql> select substring('Hello MySQL',1,5); +------------------------------+ | substring('Hello MySQL',1,5) | +------------------------------+ | Hello | +------------------------------+ 1 row in set (0.00 sec)
mysql> select ifnull('Ok','Default'); +------------------------+ | ifnull('Ok','Default') | +------------------------+ | Ok | +------------------------+ 1 row in set (0.00 sec) mysql> select ifnull('','Default'); +----------------------+ | ifnull('','Default') | +----------------------+ | | +----------------------+ 1 row in set (0.00 sec) mysql> select ifnull(null,'Default'); +------------------------+ | ifnull(null,'Default') | +------------------------+ | Default | +------------------------+ 1 row in set (0.00 sec)
C. case when then else end 需求: 查询emp表的员工姓名和工作地址 (北京/上海 —-> 一线城市 , 其他 —-> 二线城市)
1 2 3 4 5
select name, ( case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市' end ) as '工作地址' from emp;
案例:
各科考试成绩转换为优秀、及格、不及格来表示
1 2 3 4 5 6 7 8 9
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);
具体的SQL语句如下:
1 2 3 4 5 6 7 8 9 10
select id, name, (case when math >= 85 then '优秀' when math >=60 then '及格' else '不及格' end ) '数学', (case when english >= 85 then '优秀' when english >=60 then '及格' else '不及格' end ) '英语', (case when chinese >= 85 then '优秀' when chinese >=60 then '及格' else '不及格' end ) '语文' from score;
思考:
1). 数据库中,存储的是入职日期,如 2000-01-01,如何快速计算出入职天数呢? ——–> 答案: datediff 2). 数据库中,存储的是学生的分数值,如98、75,如何快速判定分数的等级呢? ———-> 答案: case ... when ...