目录
一、函数
函数 是指一段可以直接被另一段程序调用的程序或代码。
MySQL是 MySQL 数据库提供的内部函数,这些内部函数可以帮助用户更加方便地处理表中的数据。函数就像预定的公式一样存放在数据库里,每个用户都可以调用已经存在的函数来完成某些功能。
同时MySQL数据库还支持用户自己建立函数,以适应实际的业务操作。正确使用函数会让读者在编写 SQL 语句时起到事半功倍的效果。
(一)字符串函数
案例: select concat('hello','mysql'); select lower('Mysql'); select upper('hello'); select lpad('02',5,'/'); select rpad('01',10,']'); select trim(' hello mysql '); select substring('hello mysql',2,3);
案例:
#由于企业需求,企业员工号统一为5为数,不足5位数的全部在前面补0,1号员工位00001 update emp set workno = lpad(workno,5,'0');
(二)数值函数
案例:
#数值函数 #ceil select ceil(9.8); #floor select floor(6.6); #mod取余 select mod(3,4); #rand随机数 select rand(); #round取小数位数 select round(2.3434534,3);
#通过数据库数值函数生成一个随机6位数 select lpad(round(rand()*1000000),6,0);
(三)日期函数
案例:
#日期函数 #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 30 day ); #datediff相差多长时间,第一个时间减去第二个时间差 select datediff('2025-03-08','2024-03-08'); #查询员工员工入职天数,并根据入职天数倒序排序 select name,datediff(curdate() ,entrydate) as 'entrydays' from emp order by entrydays desc ;
(四)流程控制函数
案例:
#流程控制函数 #if select if (true,'ok','rrror'); #ifnull select ifnull(null,'default'); select ifnull('fghjsdak','default'); #caee when then elas end #查询emp员工表中姓名和工作地址(北京/上海----一线城市,其他为二线城市) select name, (case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市' end) as '工作地址所在低级城市' from emp;
案例:
总结:
这是以上使用到的案例语句:
select concat('hello','mysql');
select lower('Mysql');
select upper('hello');
select lpad('02',5,'/');
select rpad('01',10,']');
select trim(' hello mysql ');
select substring('hello mysql',2,3);
#由于企业需求,企业员工号统一为5为数,不足5位数的全部在前面补0,1号员工位00001
update emp set workno = lpad(workno,5,'0');
#数值函数
#ceil
select ceil(9.8);
#floor
select floor(6.6);
#mod取余
select mod(3,4);
#rand随机数
select rand();
#round取小数位数
select round(2.3434534,3);
#通过数据库数值函数生成一个随机6位数
select lpad(round(rand()*1000000),6,0);
#日期函数
#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 30 day );
#datediff相差多长时间,第一个时间减去第二个时间差
select datediff('2025-03-08','2024-03-08');
#查询员工员工入职天数,并根据入职天数倒序排序
select name,datediff(curdate() ,entrydate) as 'entrydays' from emp order by entrydays desc ;
#流程控制函数
#if
select if (true,'ok','rrror');
#ifnull
select ifnull(null,'default');
select ifnull('fghjsdak','default');
#caee when then elas end
#查询emp员工表中姓名和工作地址(北京/上海----一线城市,其他为二线城市)
select
name,
(case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市' end) as '工作地址所在低级城市'
from emp;
实例: