MySQL中的一些常用的函数
-------在后端开发中有很多查询的业务,无论是单表还是多表,有些业务逻辑没法放进sql语句中,没办法,不过也有许多查询逻辑是可以放进sql中的。下面就来梳理一些个人在日常的开发中用到的一些函数。
1、数学函数
1.1 ABS(x) 返回x的绝对值
select ABC(-3);
结果是3
1.2 AVG(字段名) 返回该字段的平均值
ps: 查询所有学生的平均年龄
table: student
姓名 | 年龄 |
---|---|
张三 | 18 |
赵四 | 19 |
王五 | 20 |
select AVG(age) from student;
结果: 19
1.3 SUM(字段名) 返回该字段的总值
ps:查询所有学生的年龄和
table: student
姓名 | 年龄 |
---|---|
张三 | 19 |
赵四 | 20 |
王五 | 21 |
select SUM(age) from student;
结果: 60
1.4 MAX(字段名) 返回该字段的最大值
ps:查询所有学生的最大年龄
table用上一个
select MAX(age) from student
结果: 21
1.5 MIN(字段名) 返回该字段的最小值
ps:查询所有学生的最小年龄
table用上一个
select MIN(age) from student
结果: 21
2、字符串函数
2.1 concat(str1,str2…) 拼接字符串
select concat('china','YYDS','!!','hello')
结果:
chinaYYDS!!hello
2.2 FORMAT(x,n)
将数字 x 进行格式化 “#,###.##”, 将 x 保留到小数点后 n 位,最后一位四舍五入
select format(345684.124567,2)
结果:
345,684.12
2.3 TRIM(str)
去掉字符串开头和末尾的空格(不会去掉中间的)
ps:
select TRIM(' RNG NB ')
结果:
RNG NB
2.4 REVERSE(str)
将字符串s的顺序反过来
select REVERSE('RNG!NB')
结果:
BN!GNR
3、日期函数
3.1 curdate()/current_date
获取当前日期
select curdate();
select current_date;
curdate后面必须加括号(),current_date后面加不加都行(下面两个也是)。
3.2 curtime()/current_time
获取当前时间
select curtime();
select current_time;
3.3 current_timestamp
获取当前日期加时间
select current_timestamp;
3.4 TIMESTAMPDIFF(day, time1,time2)
返回time2和time1差(time2-time1)的日期,day可以替换,规则如下:
SECOND:秒
MINUTE:分
HOUR:时
DAY:天
MONTH:月
YEAR:年
select TIMESTAMPDIFF(day, '2022-05-30 00:00:00', '2022-06-08 00:00:00')
结果:
8
4、高级函数
4.1 IF(expr,v1,v2)
如果表达式expr成立,返回v1,否则返回v2。
有点类似case的用法,更简单
select IF(1=1,'YES','NO')
结果:
YES
4.2 IFNULL(字段,ans)
查询时如果该字段为空就返回ans
table: student
name | age |
---|---|
alex | 17 |
jerry | 17 |
ance | |
alex | 17 |
select name,IFNULL(age,18) from student
结果:
name | age |
---|---|
alex | 17 |
jerry | 17 |
ance | 18 |
alex | 17 |
4.3 GROUP_CONCAT
待补充。。。