目录
一、字符串函数
concat(s1,s2,s3...) 字符串拼接,将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,不是0了哦
# 拼接字符串 select concat('ioi','[]','aaa');#ioi[]aaa # 转换大小写 select lower('YUYAaaaaa');#yuyaaaaaa select upper('YAssdV');#YASSDV # 填充 select lpad('io',5,'+');#+++io select rpad('p',5,'+');#p++++ # 去除空格 select trim(' uio ppp ');#uio ppp #字符串截取 select substr('abcdefgh',1,'3');#abc
二、数值函数
ceil(x) 向上取整 floor(x) 向下取整 mod(x,y) 返回x/y的模 rand() 返回0到1之间的随机数 round(x,y) 求参数x的四舍五入值,保留y位小数
select ceil(1.2);#2 select ceil(1.8);#2 select floor(1.2);#1 select floor(1.9);#1 select mod(2,8);#2 select mod(10,3);#1 select rand();#0到1之间的随机数 select round(1.787,2);#1.79 select round(1.877,0);#2
三、日期函数
curdate() 返回当前日期 curtime() 返回当前时间 now() 返回当前日期和时间 year(date) 获取指定date的月份 month(date) 获取指定date的月份 day(date) 获取指定date的日期 date_addd(date,interval_expr(year/month/day) type) 返回一个日期/时间加上一个时间间隔expr的时间值 datediff(date1,date2) 返回起始时间date1和结束时间date2之间的天数
# 获取当前的日期 select curdate(); # 获取当前的时间 select curtime(); # 获取当前的年份 select year(now()); # 获取当前的月份 select month(now()); # 获取当前是月份中的几号 select day(now()); # 查询的分别是距离当前时间7天,7年,1个月的时间 select date_add('2022-10-1',interval 7 day); select date_add('2022-10-1',interval 7 year); select date_add('2022-10-1',interval 1 month); # 查询的两个日期之间差的天数,注意是天数,而不是别的什么 select datediff('2022-10-01','2022-10-07');
四、流程控制函数
if(val,t,f) 如果val是true,则返回的是t,否则返回的是f ifnull(val1,val2) 如果val不为空,返回val1,否则返回val2 case when val1 then res1 .... else[default] end 如果val为true,返回res1...否则返回的是default默认值 case [expr] when val1 then res1 ... else[default] end 如果expr的值等于val,返回res1,...否则返回default默认值
(1)if
select if(1>2,8,9);
(2)ifnull
select ifnull(null,100); select ifnull(10,200);
(3)case when
address表:
需求:将查询表,安徽变成一线城市,上海二线城市,北京三线城市。
select name, case address when '安徽' then '一线城市' when '上海' then '二线城市' else '三线城市'end from address;
(4)case[expr] when
sp表:
:
现在给出需求:查询表20岁以下是年轻人,20岁到50是中年人,50岁以上是老年人。
select name,case when age<=20 then '年轻' when age<=50 then '中年' else '老年' end from sp;