MySQL中的函数
MySQL中的函数主要分为以下四类: 字符串函数、数值函数、日期函数、流程函数。
1、字符串函数
函数 | 功能 |
---|---|
CONCAT(S1,S2,...Sn) | 字符串拼接,将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个长度的字符串 |
结果:
select concat('Hello', ' MySQL'); # Hello MySQL
select lower('HELLO'); # hello
select upper('hello'); # HELLO
select lpad('01', 5, '-'); # ---01
select rpad('01', 5, '-'); # 01---
select trim(' Hello MySQL '); # Hello MySQL
2、数值函数
函数 | 功能 |
---|---|
CEIL(x) | 向上取整 |
FLOOR(x) | 向下取整 |
MOD(x,y) | 返回x/y的模 |
RAND() | 返回0~1内的随机数 |
ROUND(x,y) | 求参数x的四舍五入的值,保留y位小数 |
演示结果:
select ceil(1.1); # 2
select floor(1.6); # 1
select mod(5, 2); # 1
select rand(); # 0.3422266983820374
select round(3.1415926, 3); # 3.142
3、日期函数
函数 | 功能 |
---|---|
CURDATE() | 返回当前日期 |
CURTIME() | 返回当前时间 |
NOW() | 返回当前日期和时间 |
YEAR(date) | 获取指定date的年份 |
MONTH(date) | 获取指定date的月份 |
DAY(date) | 获取指定date的日期 |
DATE_ADD(date, INTERVAL expr type) | 返回一个日期/时间值加上一个时间间隔expr后的 时间值 |
DATEDIFF(date1,date2) | 返回起始时间date1 和 结束时间date2之间的天数 |
演示:
select curdate(); # 2022-08-26
select curtime(); # 23:22:44
select now(); # 2022-08-26 23:23:10
select year(now()); # 2022
select month(now()); # 8
select day(now()); # 26
select date_add(now(), interval 5 day); # 2022-08-31 23:25:25
select datediff(now(), '2022-08-31'); # -5
select datediff(now(), now()); # 0
select datediff('2022-08-31', now()); # 5