携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第31天,点击查看活动详情
一、MySQL函数概述
MySQL函数是经过编译并存储SQL语句的集合。
自定义函数与存储过程的区别:
- 自定义函数不能拥有输出参数,存储过程可以拥有输出参数。
- 自定义函数中必须包含一条 RETURN 语句。
- 可以直接对自定义函数进行调用,存储过程的调用需要使用 CALL 语句。
- 函数只会返回一个值,不允许返回一个结果集;存储过程可以返回结果集。
二、MySQL自定义函数
1、基本语法:
delimiter 符号;
2、创建函数:
-- 修改语句结束符
delimiter $$;
create function 函数名(形参) returns 返回值类型
begin
// 函数体
return 返回值数据;
end
语句结束符
-- 将语句结束符修改回来
delimiter ;
3、查看函数:
show function status [like 'pattern'];
4、调用函数:
select 函数名(实参列表);
5、删除函数:
drop function 函数名;
三、MySQL内置函数
1、字符串函数
| 函数名 | 说明 |
|---|---|
| char_length | 判断字符串的字符数 |
| length | 判断字符串的字节数,与字符集有关 |
| concat | 连接字符串 |
| insrt | 检查字符是否在目标字符串中,存在返回其位置,不存在返回 0 |
| lcase | 全部小写 |
| ltrim | 消除左边的空格 |
| left(str, length) | 左侧开始截取字符串,直到指定位置 |
| right(str, length) | 右侧开始截取字符串,直到指定位置 |
| mid | 从中间指定位置开始截取,如果不指定截取长度,直接到最后 |
| substring(str, index, [length]) | 从指定位置开始,指定截取长度 |
| substring_index(str, delim, count) | 按照关键字截取 |
select char_length('你好中国'); // 4
select length('你好中国'); // 12
select length('hello'); // 5
select char_length('hello'); // 5
select concat('你好', '中国'); // 你好中国
-- 下标从 1 开始
select instr('你好中国', '中国'); // 3
select instr('你好中国', '我'); // 0
select lcase('aBcd'); // abcd
select left('aBcd', 2); // aB
select right('abcdef', 2); // ef
select substring('abcdef', 2, 3); // bcd
select substring('abcdef', -2, 3); // ef
select ltrim(' abc d '); // abc d
select mid('你好中国', 3); // 中国
select substring_index('www.baidu.com', '.', 2); // www.baidu
select substring_index('www.baidu.com', '.', -2); // baidu.com
2、时间函数
| 函数名 | 说明 |
|---|---|
| now() | 返回当前时间,日期 时间 |
| curdate() | 当前日期 |
| curtime() | 当前时间 |
| datediff() | 判断两个日期之间的天数之差,日期使用字符串格式(用引号) |
| date_add(日期, interval 时间数字 type) | 时间增加(type: |
| unix_timestamp() | 获取时间戳 |
| from_unixtime() | 将指定时间戳转换成对应的日期时间格式 |
select now(); // 2022-04-10 22:05:38
select curdate(); // 2022-04-10
select curtime(); // 22:05:51
select datediff('2022-01-09', '2022-01-01'); // 8
select date_add('2000-10-01', interval 10 day); // 2000-10-11
select unix_timestamp(); // 1649599799
select from_unixtime(1649599799); // 2022-04-10 22:09:59
3、数学函数
| 函数名 | 说明 |
|---|---|
| abs | 绝对值 |
| ceiling | 向上取整 |
| floor | 向下取整 |
| pow | 指数 |
| rand | 随机数(0-1) |
| round | 四舍五入 |
select abs(-1); // 1
select ceiling(1.1); // 2
select floor(1.9); // 1
select pow(2, 4); // 16
select rand(); // 0.2616088308967732
select round(1.5); // 2
4、其他函数
| 函数名 | 说明 |
|---|---|
| md5() | MD5 |
| version() | 版本号 |
| database() | 显示当前所在数据库 |
| uuid() | 生成一个唯一标识符,全局唯一 |
select md5('abc'); // 900150983cd24fb0d6963f7d28e17f72
select version(); // 8.0.16
select database(); // mydatabase
select uuid(); // c44a06a2-b8d8-11ec-a53c-504259f9d746