函数是指一段可以直接被另一段程序调用的程序或代码
比如:
数据库表中,存储的是入职日期,如2001-11-12,如何快速计算入职天数?
数据库表中,存储的是学生的分数值,如98、75,如何快速判定分数的等级?

1.字符串函数

sql
-- concat
select concat('hello', 'MySQL');
-- lower
select lower('HELLO');
-- upper
select upper('hello');
-- lpad
select lpad('01', 5, '-');
-- rpad
select rpad('01', 5, '-');
-- trim
select trim(' hello mysql ');
-- subtring
select substring('hello mysql', 1, 5);
案例:

sql
-- 1.由于业务需求变更,企业员工的工号,统一为5位数,目前不足五位数的全部在前面补0, 比如1号员工的工号应该为00001
update emp set workno = lpad(workno, 5, '0');
2.数值函数

sql
-- 数值函数
-- ceil
select ceil(1.1);
-- floor
select floor(1.9);
-- mod
select mod(3, 4);
-- rand
select rand();
-- round
select round(2.345, 2);
案例:
sql
-- 通过数据库的函数,生成一个六位数的随机验证码
select lpad(round(rand()*1000000, 0), 6, '0');
3.日期函数

sql
-- 日期函数
-- curdate
select curdate();
-- curtime
select curtime();
-- now
select now();
-- YEAR MONTH DAY
select year(now());
select month(now());
select day(now());
-- date_add
select date_add(now(), interval 70 YEAR );
select date_add(now(), interval 70 month );
select date_add(now(), interval 70 day );
-- datediff
select datediff('2021-01-06', '2021-01-01');
案例:
sql
-- 查询所有员工的入职天数,并根据入职天数倒序排序。
select name, datediff(curdate(), entrydate) as 'entrydays' from emp order by entrydays desc ;
4.流程函数

sql
-- 流程控制函数
-- if
select if(false, 'ok', 'error');
-- ifnull
select ifnull('ok', 'default');
select ifnull('', 'default');
select ifnull(null, 'default');
-- case when then else end
-- 需求:查询emp表的员工姓名和工作地址(北京/ 上海 -----》 一线城市 , 其他 --------》 二线城市)
select
name,
(case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市' end) as '工作地址'
from emp;
案例:
sql
-- 案例:统计班级各个学员的成绩,展示的规则如下:
-- >= 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', 50,68,69),
(2,'MARY',80,81,82),
(3,'JACK',70,71,72);
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;
