【Mysql】数据库的内置函数
MySQL 内置函数详解
在日常数据库操作中,SQL 语句往往需要配合各种函数来处理数据。MySQL 提供了丰富的内置函数,涵盖日期、字符串、数学、系统等方面。本文将通过实例,带你快速掌握 MySQL 常用函数。
一、日期函数
MySQL 的日期函数用于获取、计算和处理日期与时间。
1.1 获取当前时间
select current_date(); -- 当前日期
select current_time(); -- 当前时间
select current_timestamp(); -- 当前时间戳
1.2 日期加减
select date_add('2017-10-28', interval 10 day); -- 2017-11-07
select date_sub('2017-10-1', interval 2 day); -- 2017-09-29
1.3 日期差值
select datediff('2017-10-10', '2016-9-1'); -- 404 天
1.4 实战案例
- 生日表
create table tmp(id int primary key auto_increment,birthday date
);
insert into tmp(birthday) values(current_date());
- 留言表
create table msg (id int primary key auto_increment,content varchar(30) not null,sendtime datetime
);
insert into msg(content,sendtime) values('hello1', now());
insert into msg(content,sendtime) values('hello2', now());-- 只显示日期部分
select content, date(sendtime) from msg;-- 查询 2 分钟内发布的帖子
select * from msg where date_add(sendtime, interval 2 minute) > now();
二、字符串函数
字符串函数主要用于处理文本内容。
2.1 常见用法
- 获取字符集
select charset(ename) from EMP;
- 拼接字符串
select concat(name, '的语文是', chinese, '分,数学是', math, '分') as 分数
from student;
- 计算字节长度
select length(name), name from student;
注意:
length()
返回的是字节数,而不是字符数。中文在 UTF-8 下通常占 3 个字节。
2.2 字符串处理
-- 替换
select replace(ename, 'S', '上海'), ename from EMP;-- 截取
select substring(ename, 2, 2), ename from EMP;-- 首字母小写
select concat(lcase(substring(ename, 1, 1)), substring(ename,2)) from EMP;
三、数学函数
MySQL 提供丰富的数学函数,常用于数值计算。
select abs(-100.2); -- 绝对值 100.2
select ceiling(23.04); -- 向上取整 24
select floor(23.7); -- 向下取整 23
select format(12.3456, 2);-- 保留两位小数 12.35
select rand(); -- 随机数
四、其它常用函数
4.1 系统函数
select user(); -- 当前用户
select database(); -- 当前数据库
4.2 加密函数
select md5('admin');
-- 21232f297a57a5a743894a0e4a801fc3select password('root');
-- *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B
4.3 空值处理
select ifnull('abc', '123'); -- abc
select ifnull(null, '123'); -- 123
总结
- 日期函数:用于获取当前时间、日期加减、差值计算。
- 字符串函数:可实现拼接、替换、截取、字节长度统计。
- 数学函数:常用于取整、格式化、生成随机数。
- 其它函数:包括系统信息、加密与空值处理。
熟练掌握这些 MySQL 内置函数,可以让你在写 SQL 时更加灵活、高效。