什么是函数

函数是指一段可以直接被另一段程序调用的程序或代码。

数据库表中,存储的是入职日期,如2000-11-12,如何快速计算入职天数???

数据库表中,存储的是学生的分数值,如98、75,如何快速判定分数的等级呢???

字符串函数

MySQL中内置了很多字符串函数

007函数 - 图1

  1. SELECT 函数(参数);

concat

  1. select concat ('hello','mysql');

Lower

  1. select lower ('HelLo');

Upper

  1. select upper ('hello');

Lpad

  1. select lpad ('01','5','-');

rpad

  1. select rpad ('01','5','-');

trim

  1. select trim(' ppp ');

Substring

  1. select substring('hello',1,5);

案例

由于业务需求变更,企业员工的工号,统一为5位数,目前不足5位数的全部在前面补0。比如:1号员T的工号应该为0001

  1. update emp set workno =lpad(workno,5,0)

数值函数

常见的数值函数 007函数 - 图2

cell

  1. select cell (1.1)

floor

  1. select cell(1.9)

mod

  1. slect mod(20,2)

rand

  1. select rand()

Round

  1. select round(3.5,1)

案例

通过数据库的函数,生成一个六位数的随机验证码

  1. select lpad(round(rand()*10000,0),6,0)

日期函数

常见的日期函数

007函数 - 图3

curdate

  1. select curdate();

curtime

  1. select curtime();

now

  1. select now();

month

  1. select month(now());

day

  1. select day(now());

Date_add

  1. select date_add(now(),50 day)

datediff

  1. select datediff('2021-12-01','2021-12-30')

案例

查询所有员工的入职天数,并根据入职天数倒序排序。

  1. select name ,datediff(curdate(),entrydate) as 'entrydays' from emp order by entrydays desc;

流程控制函数

007函数 - 图4

if

  1. select if(true,'ok','error')

ifnull

  1. select ifnull('ok','error')

case when…else end

需求:查询emp表的员工姓名和工作地址(北京/上海—->一线城市,其他——>二线城市)

  1. select name,workaddress (when '北京'then '一线城市' when '上海'then '一线城市'else '二线城市') as '工作地址' from emp;

Case when then…else end

= 85,展示优秀
= 60,展示及格
否则,展示不及格

  1. select
  2. id,
  3. name,
  4. (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 ) '文"
  5. from score;