函数–应用场景
函数—指一段可以直接被另一段程序调用的程序或代码
字符串函数
练习:
1、—concat
select concat('hello',' mysql');
2、—lower
select lower('hello');
3、—upper
select upper('Hello');
4、—lpad
select lpad('01',5,'-');
5、—rpad
select rpad('01',5,'-');
6、—trim
select trim(' Hello MySQL');
7、—substring
select substring('Hello MySQL',1,5);
8、由于业务需求变更,企业员工的工号,统一为5位数,目前不足5位数的全部在前面补0。比如:1号员工的工号应该为00001。(此处用的是数据库练习题(三)中的emp表)
update emp set workno = lpad(workno,5,'0');
数值函数
练习:
1、—ceil
select ceil(1.5);//2
select ceil(1.1);//2
2、—floor
select floor(1.9);//1
3、—mod
select mod(6,4);//2
4、—rand
select rand();
5、—round
select round(2.34,2);//2.34
select round(2.345,2);//2.35
7、通过数据库的函数,生成一个六位的随机验证码
select ipad(round(rand()*1000000,0),6,'0');
日期函数
练习:
1、—curdate()
select curdate();
2、—curtime()
select curtime();
3、—now()
select now();
4、—year,moth,day
select year(now());
select month(now());
select day(now());
5、—date_add
select date_add(now(),interval 70 day);
6、—datediff
select datediff('2021-10-01','2024-01-10');
7、查询所有员工的入职天数,并根据入职天数倒序排序
select name,datediff(curdate(),entrydate) as 'entrydays' from emp order by entrydays desc;
流程函数
练习:
1、—if
select if(true,'ok','Error');
2、—ifnull
select ifnull('ok','Default');//ok
select ifnull('','Default');//''
select ifnull(null,'Default');//Default
3、.—case when then else end
—需求:查询emp表的员工姓名和工作地址(北京/上海—>一线城市,其他—>二线城市)
select name,
(case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市' end)
as '工作地址'
from emp;
4、统计班级各个学员的成绩,展示的规则如下:>=85,展示优秀,>=60,展示及格,否则,展示不及格
例子数据:
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 >=85 then '优秀' when 60<= math then '及格' else '不及格' end) '数学',
(case when english >=85 then '优秀' when 60<= english then '及格' else '不及格' end) '英语',
(case when chinese >=85 then '优秀' when 60<= chinese then '及格' else '不及格' end) '语文'
from
score;