【MySQL数据库】函数操作
目录
1,日期函数
2,字符串函数
3,数学函数
1,日期函数
样例:
获得年月日
select current_date();
获取时分秒
select current_time();
获得时间戳
select current_timestamp();
在日期的基础上加日期
在2025年4月27日增加10天:select date_add('2025-04-27', interval 10 day);
在指定日期上增加5个月:select date_add('2025-04-27', interval 5 month);
在日期的基础上减少时间
在2025年4月27日增加10天:select date_sub('2025-04-27', interval 10 day);
在指定日期上增加5个月:select date_sub('2025-04-27', interval 5 month);
计算两个日期之间相差多少天
select datediff('2025-05-01', '2025-04-27');
在生日表中增添当前的日期
创建表结构:create table birthdays (id int primary key, birthday date);
插入数据:insert into birthdays (id,birthday) values (1,current_date());
注意:若类型合适,这里也可以插入now()、current_timestamp()。
显示出表 birthdays 的生日日期
方式一:select date(birthday) from birthdays;
方式二:select birthday from birthdays;
注意:date(datetime)语句中,只会显示 datetime 的日期部分,不会显示时间。
2,字符串函数
样例:
获取 persons 表的 name 列的每一个数据的字符集:
select charset(name) from persons;
按照指定 "x生xxx的兴趣是xxx..." 格式显示出 persons 表的信息
select concat(gender,'生',name,'的兴趣是',hobby) from persons;
查询表 persons 表中人的姓名所占的字节数
select length(name) from persons;
注意:length函数返回字符串长度,以字节为单位。如果是多字节字符则计算多 个字节数;如果是单字节字符则算作一个字节。比如:字母,数字算作一个字节, 中文表示多个字节数(与字符集编码有关)
将 student 表中 qq 列里的 1 替换成 2 ,将其显示出(表中数据没有改变)
select replace(qq, '1', '2') from student;
截取 student 表中 qq 列里的第二个字符到第三个字符,将其显示出
select substring(qq,2,2) from student;
以首字母小写的方式显示出 student 表中所有人的姓名
select concat(lcase(stustring(name,1,1)), substring(name,2)) from student;
3,数学函数
样例:
绝对值:select abs(-100.2); 输出100.2
向上取整:select ceiling(23.04); 输出24
向下取整:select floor(23.7); 输出23
保留2位小数位数(小数四舍五入):select format(12.3456, 2); 输出12.35
产生随机数:select rand(); 输出一个[0.0, 1.0)范围的数值
除了上面几个几种函数外,还有一种 user()、database() 显示当前的用户、数据库函数。