长大带给我的最大改变就是,坦然、默默、不得不接受我们以往所万万不能接受的事和物;最可悲的就是,面对现实、我们无能为力、或心有余而力不足;
可喜可贺的是,我还有时间、有想法去试着努力去改变那些还未发生的厄运;
目录
日期函数:
函数名 | 描述 |
curdate(); | 返回当前日期,格式:2000-10-24 |
curtime(); | 返回当前时间,格式:11:25:00 |
now(); | 返回当前日期+时间:格式:2022-11-09 11:26:54 |
date_add(d,INTERVAL expr type); | 计算起始日期 d 加上一个时间段后的日期 |
datediff(d1,d2); | 计算日期 d1->d2 之间相隔的天数 |
year(d); | 返回时间d所在的年份 |
month(d); | 返回时间d所在的月份 |
day(d); | 返回时间d所在的天数 |
使用案例演示:
-- 日期函数
select curdate(); -- 返回当前日期
select curtime();-- return current time;
select now(); -- 返回当前日期加时间
select year(now());-- 返回当前日期的年
select month(now());
select day(now());
select date_add(now(),interval 70 day);-- 往后推多少天、月、年;;注意date不要拼成data;
select datediff('2022-11-9','2000-9-24');
-- 函数使用案例
select name ,datediff(curdate(),entrydate) as 'entrdays' from emp order by entrdays desc;
字符串函数:
函数名 | 描述 |
concat(s1,s2...sn); | 字符串 s1,s2 等多个字符串合并为一个字符串 |
lower(str); | 将str全部转为小写 |
upper(str); | 将str全部转为大写 |
lpad(s1,len,s2); | 在字符串 s1 的开始处填充字符串 s2,使字符串长度达到 len |
rpad(s1,len,s2); | 在字符串 s1 的结尾处添加字符串 s2,使字符串的长度达到 len |
trim(str); | 去掉字符串 str开头和结尾处的空格 |
substring(s, start, length); | 从字符串 s 的 start 位置截取长度为 length 的子字符串,等同于 SUBSTR(s, start, length) |
使用案例演示:
# 字符串函数
select * from emp where name='小昭' ;
select concat('hello','mysql');
select lower('Hello');
select upper('hello');
select lpad('01',5,'-');-- 左填充
select rpad('01',5,'-');-- 右填充
select trim(' hello mysql ');-- 取出头尾部的空格
select substring('hello mysql',1,4);-- 字符串截取
-- 函数使用案例
update emp set workno = lpad(workno,6,'-');
select name,workno from emp;
数值函数:
函数名 | 描述 |
ceil(x); | 向上取整 |
floor(x); | 向下取整 |
mod(x,y); | 返回 x 除以 y 以后的余数 |
rand(); | 返回 0 到 1 的随机数 |
round(x,y); | 对x四舍五入保留y位小数 |
使用案例演示:
-- 数值函数
select ceil(2.3);-- 向上取整
select floor(2.3);-- 向下取整
select mod(2,3); -- 模运算取余
select rand();-- 取随机数
select round(2.346,2);-- 四舍五入,保留几位小数
-- 函数使用案例
select rpad( round(rand()*100000,0),6,0);-- 函数之间可以套用
流程控制函数:
函数名 | 描述 |
if(expr,v1,v2); | 如果表达式 expr 成立,返回结果 v1;否则,返回结果 v2。 |
ifnull(v1,v2); | 如果 v1 的值不为 NULL,则返回 v1,否则返回 v2。 |
CASE WHEN [val1 ] THEN [res1]..ELSE [default] END | 如果val1为true,返回res1,..否则返回defaut默认值 |
CASE [ expr] WHEN [vall ] THEN [res1]. ELSE [default] END | 如果expr的值等于val1,返回res1,..否则返回defaut默认值 |
使用案例演示:
-- 流程控制函数
select if(true,'ok','error');
select ifnull('ok','defult');
select ifnull('','defult');
-- 下面这个函数比较难理解,要掌握好格式;
select name,( case workaddress when '北京'then'一线城市' when'上海'then '二线城市'else '三线城市'end)as '工作地址' from emp;
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;