一、定义
函数 是指一段可以直接被另一段程序调用的程序或代码。 也就意味着,这一段程序或代码MySQL
中 已经给我们提供了,我们要做的就是在合适的业务场景调用对应的函数完成对应的业务需求即可。
二、字符串函数
2.1、案例
2.1.1、concat 字符串拼接
select concat('Hello' , ' MySQL');
2.1.2、lower全部转小写
select lower('Hello');
2.1.3、upper 全部转大写
select upper('Hello');
2.1.4、lpad 左填充
select lpad('01', 5, '-');
2.1.5、rpad 右填充
select rpad('01', 5, '-');
2.1.6、trim去除空格
select trim(' Hello MySQL ');
2.1.7、substring 截取子字符串
select substring('Hello MySQL',1,5);
2.1.8、工号填充
由于业务需求变更,企业员工的工号,统一为5 位数,目前不足 5 位数的全部在前面补 0 。比如: 1 号员 工的工号应该为00001

三、数值函数
3.1、常见的数值函数
3.2、案例
3.2.1、ceil向上取整
select ceil(1.1);
3.2.2、floor向下取整
select floor(1.9);
3.2.3、mod取模
select mod(7,4);
3.2.4、rand获取随机数
select rand();
3.2.5、round四舍五入
select round(2.344,2);
3.2.6、通过数据库的函数,生成一个六位数的随机验证码
思路:
获取随机数可以通过 rand() 函数,但是获取出来的随机数是在 0-1 之间的,所以可以在其基础上乘以 1000000 ,然后舍弃小数部分,如果长度不足 6 位,补 0
select lpad(round(rand()*1000000 , 0), 6, '0');
四、日期函数
4.1、常见的日期函数
4.2、案例
4.2.1、curdate当前日期
select curdate();
4.2.2、curtime当前时间
select curtime();
4.2.3、now当前日期和时间
select now();
4.2.4、YEAR , MONTH , DAY当前年、月、日
select YEAR(now());
select MONTH(now());
select DAY(now());
4.2.5、date_add增加指定的时间间隔
select date_add(now(), INTERVAL 70 YEAR );
4.2.6、datediff获取两个日期相差的天数
select datediff('2021-10-01', '2021-12-01');
4.2.7、查询所有员工的入职天数,并根据入职天数倒序排序。
select name, datediff(curdate(), entrydate) as 'entrydays' from employee order by
entrydays desc;
五、流程函数
5.1、定义
流程函数也是很常用的一类函数,可以在
SQL
语句中实现条件筛选,从而提高语句的效率
5.2、常见的流程函数
5.3、案例
5.3.1、if
select if(false, 'Ok', 'Error');
5.3.2、ifnull
select ifnull('Ok','Default');
select ifnull('','Default');
select ifnull(null,'Default');
5.3.3、case when then else end
# 需求:查询employee表的员工姓名和工作地址 (北京/上海 ----> 一线城市 , 其他 ----> 二线城市)
select
name,
(case workaddress
when '北京' then '一线城市'
when '上海' then '一线城市'
else '二线城市'
end) as '工作地址'
from employee;
5.3.4、计算学生考试成绩等级
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 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;