一、字符串函数
1.concat(s1,s2,...,sn) 将s1,s2,...,sn拼接成一个字符串
示例:select concat('今天','真是个','好天气'); 得到"今天真是个好天气"
2.lower(str) 将字符串str的字母全部转化成小写
示例:select lower('WHAT'); 得到"what"
3.upper(str) 将字符串str的字母全部转化成大写
示例:select lower('what'); 得到"WHAT"
4.lpad(str,n,pad) 左填充,用字符串pad在字符串str的左边进行填充,使填充后的字符串达到n个字符的长度
示例:select lpad('999',6,'3'); 得到"333999"
5.rpad(str,n,pad) 右填充,用字符串pad在字符串str的右边进行填充,使填充后的字符串达到n个字符的长度
示例:select rpad('333',6,'9'); 得到"333999"
6.trim(str) 去掉字符串str头部和尾部的空格
示例:select trim(' whatever it takes '); 得到"whatever it takes"
7.substring(str,start,length) 返回字符串str从start起始的长度为length的字符串
示例:select substring('whatever it takes',1,8); (字符串第一个字符的索引是1) 得到"whatever"
二、数值函数
1.celi(x) 向上取整
示例:select ceil(1.1); 得到"2"
2.floor(x) 向下取整
示例:select floor(1.9); 得到"1"
3.mod(x,y) 返回x÷y得到的余数
示例:select mod(4,5); 得到"4",因为4÷5=0......4
select mod(5,4); 得到"1",因为5÷4=1......1
4.rand() 返回0~1内的随机数
示例:select rand(); 得到"0.911349413457262"
5.round(x,y) 返回x经四舍五入得到的值,保留y位小数
示例:select round(3.67,1); 得到"3.7"
三、日期函数
1.curdate() 返回当前日期
示例:select curdate(); 得到"2024-8-29"
2.curtime() 返回当前时间
示例:select curtime(); 得到"10:28:14"
3.now() 返回当前日期和时间
示例:select now(); 得到"2024-08-29 10:28:14"
4.year(date) 获取日期date的年份
示例:select year('2024-08-29'); 得到"2024"
5.month(date) 获取日期date的月份
示例:select month('2024-08-29'); 得到"8"
6.day(date) 获取日期date的那一天
示例:select day('2024-08-29'); 得到"29"
7.date_add(date,interval expr type) 获取某一时间date以某单位type加上间隔时间expr后得到的时间
示例:select date_add('2024-08-29',interval 20 year); 得到"2044-08-29"
8.datediff(date1,date2) 返回时间date1和时间date2中间间隔的天数,date2-date1
示例:select datediff('2024-08-31','2024-08-01'); 得到"30"
select datediff('2024-08-01','2024-08-31'); 得到"-30"
四、流程函数
1.if(value,t,f) 如果value为true,返回t,否则返回f
示例:select if(false,'正确的','错误的'); 得到"错误的"
select if(false,111,000); 得到"000"
2.ifnull(value1,value2) 如果value1值不为空,返回value1,否则返回value2
示例:select ifnull('正确的','错误的'); 得到"正确的"
select ifnull('','错误的'); 得到""
select ifnull(null,"错误的"); 得到"错误的"
3.case when value1 then result1 when value2 then result2 ... else default end 当value1为true时,返回result1;当value2为true时,返回result2......否则返回默认值default。其中value1,value2等可以是值,也可以是表达式
示例:select score,case when score >= 90 then 'A' when score >= 80 then 'B' when score >= 70 then 'C' when score >= 60 then 'D' else 'F' end as grade from students;
4.case expr when value1 then result1 when value2 then result2 ... else default end 如果expr的值等于value1,返回result1;如果expr的值等于value2,返回result2......否则返回默认值default。其中value1,value2等可以是值,也可以是表达式
示例:select case region when '北京' then '中国' when '华盛顿' then '美国' end as nations from map
五、聚合函数
需要注意的是,null不参与所有聚合函数的运算。以下面统计数量为例,若有几个学生未被分配学号,则使用count(idcard)查询出来的结果会小于真实学生个数,这种情况下可使用count(*)通过查询students表中的行数来确定学生个数
1.count 统计数量
示例:select count(idcard) from students; 统计学生学号以统计学生个数
2.max 求最大值
示例:select max(age) from students; 统计学生中的最大年龄
3.min 求最小值
示例:select min(age) from students; 统计学生中的最小年龄
4.avg 求平均值
示例:select avg(age) from students; 统计学生们的平均年龄
5.sum 求和
示例:select sum(price) from shopping; 统计商品的价格总和