MySQL-函数

发布时间:2020-08-15 20:17:37 作者:元婴期
来源:网络 阅读:400

一、内置函数

官方文档:https://dev.mysql.com/doc/refman/5.7/en/func-op-summary-ref.html

MySQL常用内置函数:
CHAR_LENGTH(str):返回值为传入字符串的长度,长度的单位为字符

CONCAT(str1,str2,...):字符串拼接

CONCAT_WS(separator,str1,str2,...):可自定义连接符的字符串拼接

示例:
mysql> select concat_ws('-','admin','123');
+------------------------------+
| concat_ws('-','admin','123') |
+------------------------------+
| admin-123                    |
+------------------------------+

CONV(num,from_base,to_base):进制转换

示例:将20从十进制转换为二进制
mysql> select conv(20,10,2);
+---------------+
| conv(20,10,2) |
+---------------+
| 10100         |
+---------------+
1 row in set (0.00 sec)

INSERT(str,x_path,y_len,new_str):指定位置插入字符串

示例:
mysql> select insert('1234567','2','3','new');
+---------------------------------+
| insert('1234567','2','3','new') |
+---------------------------------+
| 1new567                         |
+---------------------------------+
1 row in set (0.00 sec)

INSTR(str,substr):返回字符串 str 中子字符串的第一个出现位置

LOWER(str):将字符串str变小写
UPPER(str):将字符串str变大写

TRIM(str):返回字符串str并删除首尾部空格字符
LTRIM(str):返回字符串str并删除首部空格字符

示例:
mysql> select ltrim('  1 2 3  ');
+--------------------+
| ltrim('  1 2 3  ') |
+--------------------+
| 1 2 3              |
+--------------------+

RTRIM(str):返回字符串str并删除尾部空格字符

LEFT(str,len):返回字符串str左边len个字符,len为null则返回null
RIGHT(str,len):返回字符串str右边len个字符,len为null则返回null

REPLACE(str,old_str,new_str):new_str字符串替换old_str字符串
REVERSE(str):返回字符串 str ,顺序和字符顺序相反
REPEAT(str,count):返回重复count次数的字符串str

示例:
mysql> select repeat('hey',10);
+--------------------------------+
| repeat('hey',10)               |
+--------------------------------+
| heyheyheyheyheyheyheyheyheyhey |
+--------------------------------+

SUBSTRING(str,pos,len):返回字符串str中从位置pos起,长度为len的子字符串

RPAD(str,len,pad):用pad对str字符串从右边开始填充,直到len长度
LPAD(str,len,pad):用pad对str字符串从左边开始填充,直到len长度

示例:
mysql> select lpad('hello',10,'#');
+----------------------+
| lpad('hello',10,'#') |
+----------------------+
| #####hello           |
+----------------------+

二、自定义函数

MySQL自定义函数存储着一系列的sql语句,与存储过程类似,但不同的是函数只会返回一个值,而存储过程不仅可以有返回值,还有结果集的输出。

1、创建函数

f1函数可以传入两个int类型的值,函数返回结果也是int类型
delimiter \\
create function f1( i1 int, i2 int)
returns int
BEGIN
    declare num int;
    set num = i1 + i2;
    return(num);
END \\
delimiter ;

2、执行函数

#查询使用
select f1(10,11);
#sql语句块内赋值使用
declare num int;
select nid into num from student where nid = 1;

3、删除函数

drop function func_name;
推荐阅读:
  1. Mysql-服务端-扩展配置
  2. Mysql-主从-binlog-格式,参数(三)

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

函数 mysql

上一篇:SSL证书端口指南

下一篇:Windows平台SSH服务器搭建

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》