MySQL-函数

第六节.MySQL-函数

  • 聚合函数在第四节介绍过
字符串函数
  1. 常见的字符串函数
函数 功能
concat(s1,s2...sn) 字符串拼接
lower(str) 将str转换为小写
upper(str) 将str转换为大写
lpad(str,n,pad) 左填充,用字符串pad对str的左边进行填充,达到n个字符串长度
rpad(str,n,pad) 右填充,用字符串pad对str的右边进行填充,达到n个字符串长度
trim(str) 去掉字符串头部和尾部的空格
substring(str,start,len) 返回字符串str从start位置起的len个长度的字符串 字符串从1开始计数
  1. 语法
select 函数(参数);
  1. 练习
  • 由于企业需求,员工工号统一改为五位数,不足五位数的前面补0,eg:1->00001
update emp set worknumber = lpad(worknumber,5,0);
数值函数
  1. 常见的数值函数
函数 功能
ceil(x) 向上取整
floor(x) 向下取整
mod(x) 返回x/y的模
rand() 返回0~1的内随机数
round(x,y) 求参数x的四舍五入的值,保留y位小数
  1. 语法
select 函数(参数);
  1. 练习
  • 通过数据库函数,生成一个六位数随机验证码
select lpad(round(rand()*1000000,0),6,0);
#0.019255会导致第一个0被省略,需要补充左边的0修补bug
日期函数
  1. 常见的日期函数
函数 功能
curdate() 返回当前日期
curtime() 返回当前时间
now() 返回当前日期和时间
year(date) 获取指定date的年份
month(date) 获取指定date的月份
day(date) 获取指定date的日期
date_add(date,interval expr type) 返回一个日期/时间值加上一个时间间隔expr后的时间值
datediff(date1,date2) 返回起始时间date1和结束时间date2之间的天数
  1. 语法
select 函数(参数);
  1. 练习
  • 查询所有员工的入职天数并且根据入职天数进行倒序排列
select name,datediff(curdate(),entrydate) as '入职天数' from emp order by '入职天数' desc;
流程函数
  1. 常见流程函数
函数 功能
if(value,t,f) 如果value为true,则返回t,否则返回f
ifnull(value1,value2) 如果value不为空,返回value1,否则返回value2
case when [val1] then [rea1] ... else [default] end 如果val1为true,返回res1,...否则返回default默认值
case [expr] when [val1] then [res1] ... else [default] end 如果expr的值等于val1,返回res1,...否则返回default默认值
  1. 语法
select 函数();
  1. 练习
  • 查询员工表的员工姓名和工作地址(北京/上海--->一线城市 , 其他--->二线城市)
select
    name,
    (case workaddress when '上海' then '一线城市' when '北京' then '一线城市' else '二线城市' end) as '工作地址'
from employees;
  • 统计班级各个学员的成绩,展示的规则如下:
    1. >=85,展示优秀
    2. >=60,展示及格
    3. 否则,展示不及格
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);
id name math english chinese
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) as '数学等级',
    (case when english>=85 then '优秀' when english>=60 then '及格' else '不及格' end) as '英语等级',
    (case when chinese>=85 then '优秀' when chinese>=60 then '及格' else '不及格' end) as '语文等级'
from score;

本文章使用limfx的vscode插件快速发布