MySQL 存储过程与函数(精简笔记)

MySQL
373
0
0
2023-02-13

MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品。MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MySQL是最好的 RDBMS (Relational Database Management System,关系数据库管理系统) 应用软件之一,该笔记用于生产环境快速查阅.

♥ 文章声明 ♥ 该系列文章部分文字描述,参考于以下文献,化繁为简. 《MySQL5.7从入门到精通》 - 刘增杰

简单的说,存储过程就是一条或者多条SQL语句的集合,可以理解为脚本,但是起作用不仅限于批处理,下面我们将重点学习如何使用创建存储函数和过程,变量的调用查看等,存储过程是MySQL的一个重点内容.

存储程序可以分为存储过程和函数,MySQL中创建存储过程和函数使用的语句分别是:CREATE PROCEDURECREATE FUNCTION.使用CALL语句来调用存储过程,只能用输出变量返回值.函数可以从语句外调用(即通过引用函数名),也能返回标量值,存储过程也可以调用其他存储过程.

创建存储过程

创建存储过程,需要使用create procedure语句,其基本语法格式如下:

create procedure proc_name ([proc_parameter])
	[characteristics ...] routine_body

如上,create procedure为用来创建存储函数的关键字,proc_name为存储过程名称,proc_parameter为指定存储过程的参数列表,列表的形式如下所示:

[ IN | OUT | INOUT ] param_name type

其中,IN表示输入的参数,OUT表示输出的参数,INOUT表示即可以输入也可以输出,param_name表示参数名称,type表示参数的类型,该类型可以使MySQL数据库中任意的类型.

创建简单存储过程: 创建一个存储过程Proc(),实现查询lyshark数据表的所有字段.

MariaDB [lyshark]> delimiter //
MariaDB [lyshark]> create procedure Proc()
    -> BEGIN
    -> select * from lyshark;
    -> END //
Query OK, 0 rows affected (0.00 sec)

MariaDB [lyshark]> delimiter ;
MariaDB [lyshark]> call Proc;

以上存储过程,只是执行了查询语句的操作,delimiter语句的作用是方式结束符与冒号相冲突,当我们写完存储过程时,应该使用相同的闭合语句恢复.

创建带参存储过程: 创建一个存储过程,查询lyshark表中记录,过程名称为CountProc,并使用count(*)计算后把结果放入参数param1中,SQL语句如下:

MariaDB [lyshark]> delimiter //
MariaDB [lyshark]> create procedure CountProc(OUT param1 INT)
    -> BEGIN
    -> select count(*) into param1 from lyshark;
    -> END //
Query OK, 0 rows affected (0.01 sec)

MariaDB [lyshark]> delimiter ;

当我们想要调用上面的存储过程是,需要指定一个变量名来接收返回结果,此处指定为temp.

MariaDB [lyshark]> call CountProc(@temp);
Query OK, 1 row affected (0.00 sec)

MariaDB [lyshark]> select @temp;
+-------+
| @temp |
+-------+
|    17 |
+-------+
1 row in set (0.00 sec)

创建带参存储过程: 创建一个存储过程CountProc1,然后调用这个过程,定义SQL语句如下:

MariaDB [lyshark]> delimiter //
MariaDB [lyshark]> create procedure CountProc1(IN id int,OUT temp INT)
    -> BEGIN
    -> select count(*) into temp from lyshark where Gid=id;
    -> END //
Query OK, 0 rows affected (0.00 sec)

MariaDB [lyshark]> delimiter ;

接着我们调用CountProc1这个存储过程,并给它传递相应的参数.

MariaDB [lyshark]> select count(*) from lyshark where Gid=101;
+----------+
| count(*) |
+----------+
|        3 |
+----------+
1 row in set (0.00 sec)

MariaDB [lyshark]> call CountProc1(101,@num);
Query OK, 1 row affected (0.00 sec)

MariaDB [lyshark]> select @num;
+------+
| @num |
+------+
|    3 |
+------+
1 row in set (0.00 sec)

创建存储函数

存储函数的使用方法与MySQL内部函数的使用方法是一样的,在MySQL中,用户自己定义的存储函数与MySQL内部函数是一个性质的.区别在于,存储函数是用户自己定义的,而内部函数则是开发者编写的.

创建存储函数: 创建储存函数CountProc2,然后调用这个函数,SQL语句如下:

MariaDB [lyshark]> delimiter //
MariaDB [lyshark]> create function CountProc2(myid INT)
    -> returns int
    -> BEGIN
    -> return(select count(*) from lyshark where Gid=myid);
    -> END //
Query OK, 0 rows affected (0.02 sec)

MariaDB [lyshark]> delimiter ;

接着我们来调用这个存储函数,SQL语句如下:

MariaDB [lyshark]> select CountProc2(101);
+-----------------+
| CountProc2(101) |
+-----------------+
|               3 |
+-----------------+
1 row in set (0.00 sec)

以上可以看出,返回结果,虽然存储函数和存储过程的定义稍有不同,但是可以实现相同功能.

创建存储函数: 创建名称为NameZip,该函数返回select语句查询结果,数值类型为字符串,SQL语句如下:

MariaDB [lyshark]> delimiter //
MariaDB [lyshark]> create function NameZip()
    -> returns char(50)
    -> return (select s_name from suppliers where s_call='4521');
    -> //
Query OK, 0 rows affected (0.00 sec)

MariaDB [lyshark]> delimiter ;

调用一下看看效果,SQL语句如下.

MariaDB [lyshark]> select s_name from suppliers where s_call ='4521';
+------------+
| s_name     |
+------------+
| FastFruit. |
+------------+
1 row in set (0.00 sec)

MariaDB [lyshark]> select NameZip();
+------------+
| NameZip()  |
+------------+
| FastFruit. |
+------------+
1 row in set (0.00 sec)

如果在存储函数中的RETURN语句返回一个类型不同于函数的型的值,返回值将被强制为恰当的类型.

提示:指定参数为IN,OUT或者INOUT只对PROCEDURE是合法的.FUNCTION中总是默认为IN参数.RETURNS子句只能对FUNCTION做指定,对函数而言这是强制的.它用来指定函数的返回类型,而且函数体必须包含一个RETURN value语句.

声明使用变量

变量可以在子程序中声明并使用,这些变量的作用范围实在BEGIN...END程序中,本小姐将介绍定义和赋值一个变量,定义变量的语句如下:

DECLARE var_name[,varname]...date_type [DEFAULT value];

如上,var_name为局部变量名称,DEFAULT value子句给变量提供一个默认值,值除了可以被声明为一个常数之外,还可以被指定为一个表达式,如果没有DEFAULT子句,初始值为NULL.

定义变量: 定义名称为myparam的变量,类型为INT,默认值设置为100,只能在过程中使用.

DECLARE myparam INT DEFAULT 100;
DECLARE charsss char DEFAULT 'hello';

变量赋值: 定义3个变量,分别为var1,var2,var3,数据类型为INT,使用SET为变量赋值,代码如下:

DECLARE var1,var2,var3 INT;

MariaDB [lyshark]> set @var1=10,@var2=30;
Query OK, 0 rows affected (0.01 sec)

MariaDB [lyshark]> set @var3=@var1+@var2;
Query OK, 0 rows affected (0.00 sec)

MariaDB [lyshark]> select @var3;
+-------+
| @var3 |
+-------+
|    40 |
+-------+
1 row in set (0.00 sec)

使用数据光标

查询语句可能返回多条记录,如果数据量非常大,需要在存储过程和函数中使用光标来逐条读取查询结果集中的记录,光标必须在声明处理程序之前被声明,并且变量和条件还必须在声明光标或处理程序之前被声明.

声明光标: 声明名称为cursor_lyshark的光标,SQL代码如下:

declare cursor_lyshark cursor for select Name,Price from lyshark;

打开光标: 打开名称为cursor_lyshark的光标,SQL代码如下:

open cursor_lyshark

使用光标: 使用名称为cursor_lyshark的光标,将查询出的数据存入lyshark_namelyshark_price这两个变量中.

fetch cursor_lyshark into lyshark_name,lyshark_price;

关闭光标: 关闭名称为cursor_lyshark的光标文件.

close cursor_lyshark

使用流程控制

流程控制语句用来根据条件控制语句的执行,MySQL中用来构造控制流程的语句有:IF,CASE,LOOP,LEAVE,ITERATE,REPEAT,WHILE等,每个流程中可能包含一个单独的语句,或者是使用BEGIN...END构造的复合语句,构造可以被嵌套.

IF-THEN-ELSE条件语句: IF语句用来判断条件分支

首先传递一个数值,接收到parameter变量里,然后自增+1,并判断,如果var=0则返回系统时间,var=1则返回系统日期.

CREATE PROCEDURE proc_1(IN parameter int)
BEGIN
    DECLARE var int;
    SET var=parameter+1;
		
		IF var=0
		THEN
				select CURRENT_TIME();
		ELSEIF var=1
		THEN
				select CURRENT_DATE();
		END IF;
  END

接着我们编译这段过程,并测试依次传入temp=-1temp=1.

MariaDB [lyshark]> set @temp=0;
Query OK, 0 rows affected (0.00 sec)

MariaDB [lyshark]> call proc_1(@temp);
+----------------+
| CURRENT_DATE() |
+----------------+
| 2018-12-28     |
+----------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

MariaDB [lyshark]> set @temp=-1;
Query OK, 0 rows affected (0.00 sec)

MariaDB [lyshark]> call proc_1(@temp);
+----------------+
| CURRENT_TIME() |
+----------------+
| 07:23:04       |
+----------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

CASE-WHEN-THEN-ELSE语句: 另一个进行条件判断的语句,条件判断分支结构

 CREATE PROCEDURE proc_2 (IN parameter INT)
    BEGIN
      DECLARE var INT;
      SET var=parameter+1;
      CASE var
        WHEN 0 THEN
          select "这个数值是0呀";
        WHEN 1 THEN
          select "这个数值是1呀";
        ELSE
          select "这个数值是其他呀";
      END CASE ;
    END ;
MariaDB [lyshark]> set @temp=0;
Query OK, 0 rows affected (0.00 sec)

MariaDB [lyshark]> call proc_2(@temp);
+---------------------+
| 这个数值是1|
+---------------------+
| 这个数值是1|
+---------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

MariaDB [lyshark]> set @temp=-1;
Query OK, 0 rows affected (0.00 sec)

MariaDB [lyshark]> call proc_2(@temp);
+---------------------+
| 这个数值是0|
+---------------------+
| 这个数值是0|
+---------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

MariaDB [lyshark]> set @temp=-9999;
Query OK, 0 rows affected (0.00 sec)

MariaDB [lyshark]> call proc_2(@temp);
+--------------------------+
| 这个数值是其他呀         |
+--------------------------+
| 这个数值是其他呀         |
+--------------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

LOOP语句: 用于循环执行重复语句,LOOP只会创建一个循环过程,并不会判断.

首先使用LOOP语句进行循环操作,id值小于等于5之前,将重复执行循环过程,代码如下:

CREATE PROCEDURE proc_4()
	BEGIN
      DECLARE id INT;
      SET id=0;
      LOOP_LABLE:LOOP
		SELECT "这里开始计数";
        SET id=id+1;
        IF id >=5 THEN
          LEAVE LOOP_LABLE;  #退出循环
        END IF;
      END LOOP;
	END;

WHWHILE-DO…END-WHILE语句: 流程循环语句.

CREATE PROCEDURE proc_4()
    BEGIN
      DECLARE var INT;
      SET var=0;
      WHILE var<6 DO
        select "循环判断";
        SET var=var+1;
      END WHILE ;
    END;

ITERATE语句: 通过引用复合语句的标号,来从新开始复合语句

CREATE PROCEDURE proc_5()
  BEGIN
    DECLARE v INT;
    SET v=0;
    LOOP_LABLE:LOOP
      IF v=3 THEN
        SET v=v+1;
        ITERATE LOOP_LABLE;
      END IF;
      INSERT INTO t VALUES(v);
      SET v=v+1;
      IF v>=5 THEN
        LEAVE LOOP_LABLE;
      END IF;
    END LOOP;
  END;

REPEAT语句: 此语句的特点是执行操作后检查结果

CREATE PROCEDURE proc_6 ()
    BEGIN
      DECLARE v INT;
      SET v=0;
      REPEAT
        INSERT INTO t VALUES(v);
        SET v=v+1;
        UNTIL v>=5
      END REPEAT;
    END;

查看删除过程

MySQL中,用户可以使用SHOW STATUS语句SHOW CREATE语句来查看存储过程和函数,也可以直接从系统的information_schema数据库中查询

show status查看存储过程:

MariaDB [lyshark]> show procedure status like 'p%' \G

*************************** 1. row ************************
                  Db: lyshark
                Name: proc_1
                Type: PROCEDURE
             Definer: lyshark@%
            Modified: 2018-12-28 21:16:26
             Created: 2018-12-28 21:16:26
       Security_type: DEFINER
             Comment:
character_set_client: utf8mb4
collation_connection: utf8mb4_general_ci
  Database Collation: latin1_swedish_ci
12 rows in set (0.00 sec)

show create查看过程与函数:

MariaDB [lyshark]> show create function lyshark.NameZip;
+----------+----------+--------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| Function | sql_mode | Create Function                                                                                                                                  | character_set_client | collation_connection | Database Collation |
+----------+----------+--------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| NameZip  |          | CREATE DEFINER=`root`@`localhost` FUNCTION `NameZip`() RETURNS char(50) CHARSET latin1
return (select s_name from suppliers where s_call='4521') | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
+----------+----------+--------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+

select 查询存储过程:

MariaDB [lyshark]> select name,created from mysql.proc where db="lyshark" and type="PROCEDURE";
+------------+---------------------+
| name       | created             |
+------------+---------------------+
| CountProc  | 2018-12-28 04:19:58 |
| CountProc1 | 2018-12-28 04:31:10 |
| Proc       | 2018-12-28 03:47:30 |
| proc11111  | 2018-12-28 21:24:19 |
| proc3      | 2018-12-28 05:34:18 |
| proc4      | 2018-12-28 05:37:10 |
| proc8      | 2018-12-28 21:27:12 |
| proc_1     | 2018-12-28 07:20:08 |
| proc_111   | 2018-12-28 21:14:01 |
| proc_1111  | 2018-12-28 21:14:16 |
| proc_2     | 2018-12-28 07:27:32 |
| proc_3     | 2018-12-28 07:35:11 |
| proc_4     | 2018-12-28 21:15:40 |
| proc_444   | 2018-12-28 21:16:26 |
| wang       | 2018-12-28 04:19:07 |
| wang1      | 2018-12-28 04:25:30 |
+------------+---------------------+
16 rows in set (0.00 sec)

select 查询存储函数:

MariaDB [lyshark]> select name,created from mysql.proc where db="lyshark" and type="FUNCTION";
+------------+---------------------+
| name       | created             |
+------------+---------------------+
| CountProc2 | 2018-12-28 05:04:28 |
| NameZip    | 2018-12-28 05:16:35 |
+------------+---------------------+
2 rows in set (0.00 sec)

show语句的其他用法:

MariaDB [lyshark]> show procedure status;
MariaDB [lyshark]> show function status;

删除过程与函数:

drop procedure lyshark;
drop function countproc;

常用内置函数

函数表示对输入参数值返回一个具有特定关系的值,MySQL提供了大量丰富的函数,在进行数据库管理以及数据的查询和操作时将会经常用到各种函数.通过对数据的处理,数据库功能可以变得更加强大,更加灵活地满足不同用户的需求.各类函数从功能方面主要分为以下几类:数学函数、字符串函数、日期和时间函数、条件判断函数、系统信息函数和加密函数等.下面我们就来介绍一些基础函数的使用.

◆数学函数◆

绝对值函数:abx(x)

MariaDB [lyshark]> select abs(2) , abs(-10.5) ,abs(-100);
+--------+------------+-----------+
| abs(2) | abs(-10.5) | abs(-100) |
+--------+------------+-----------+
|      2 |       10.5 |       100 |
+--------+------------+-----------+
1 row in set (0.00 sec)

平方根函数:sqrt(x)

MariaDB [lyshark]> select sqrt(10) , sqrt(50) , sqrt(-10);
+--------------------+--------------------+-----------+
| sqrt(10)           | sqrt(50)           | sqrt(-10) |
+--------------------+--------------------+-----------+
| 3.1622776601683795 | 7.0710678118654755 |      NULL |
+--------------------+--------------------+-----------+
1 row in set (0.00 sec)

获取整数的函数:ceil(x),ceiling(x),floor(x)

MariaDB [lyshark]> select ceil(-3.35) , ceiling(3.35) , floor(3.35);
+-------------+---------------+-------------+
| ceil(-3.35) | ceiling(3.35) | floor(3.35) |
+-------------+---------------+-------------+
|          -3 |             4 |           3 |
+-------------+---------------+-------------+
1 row in set (0.00 sec)

获取随机数函数:rand(),rand(x)

MariaDB [lyshark]> select rand() , rand(10);
+--------------------+--------------------+
| rand()             | rand(10)           |
+--------------------+--------------------+
| 0.5317976954689227 | 0.6570515219653505 |
+--------------------+--------------------+
1 row in set (0.00 sec)

其他函数:round(x),round(x,y),runcate(x,y)

MariaDB [lyshark]> select round(-1.14) , round(1.14) , round(1.66);        #对数据进行四舍五入
+--------------+-------------+-------------+
| round(-1.14) | round(1.14) | round(1.66) |
+--------------+-------------+-------------+
|           -1 |           1 |           2 |
+--------------+-------------+-------------+
1 row in set (0.00 sec)

MariaDB [lyshark]> select round(1.38,1) , round(232.38989,3);              #对指定小数点后几位进行四舍五入
+---------------+--------------------+
| round(1.38,1) | round(232.38989,3) |
+---------------+--------------------+
|           1.4 |            232.390 |
+---------------+--------------------+
1 row in set (0.00 sec)

MariaDB [lyshark]> select truncate(1.31,1) , truncate(20.9999,2);           #截断操作,y参数为保留小数点后几位
+------------------+---------------------+
| truncate(1.31,1) | truncate(20.9999,2) |
+------------------+---------------------+
|              1.3 |               20.99 |
+------------------+---------------------+
1 row in set (0.00 sec)

◆字符串函数◆

计算字符串长度:CHAR_LENGTH,字节长度:LENGTH(str)

MariaDB [lyshark]> select CHAR_LENGTH('date'),CHAR_LENGTH('egg');
+---------------------+--------------------+
| CHAR_LENGTH('date') | CHAR_LENGTH('egg') |
+---------------------+--------------------+
|                   4 |                  3 |
+---------------------+--------------------+
1 row in set (0.00 sec)

MariaDB [lyshark]> select LENGTH('date'),LENGTH('egg');
+----------------+---------------+
| LENGTH('date') | LENGTH('egg') |
+----------------+---------------+
|              4 |             3 |
+----------------+---------------+
1 row in set (0.00 sec)

MariaDB [lyshark]>

合并字符串函数:CONCAT()

MariaDB [lyshark]> select CONCAT('hello','lyshark'),CONCAT('my',NULL,'SQL');
+---------------------------+-------------------------+
| CONCAT('hello','lyshark') | CONCAT('my',NULL,'SQL') |
+---------------------------+-------------------------+
| hellolyshark              | NULL                    |
+---------------------------+-------------------------+
1 row in set (0.00 sec)

字符串替换:INSERT(s1,len,s2) 将从Quest替换,从第二个字符开始,一直替换三个.

MariaDB [lyshark]> select insert('Quest',2,3,'what') ;
+----------------------------+
| insert('Quest',2,3,'what') |
+----------------------------+
| Qwhatt                     |
+----------------------------+
1 row in set (0.00 sec)

大小写转换:LOWER(str),LCASE(str) 将大写转换成小写

MariaDB [lyshark]> select LOWER('LYSHARK'),LCASE('well');
+------------------+---------------+
| LOWER('LYSHARK') | LCASE('well') |
+------------------+---------------+
| lyshark          | well          |
+------------------+---------------+
1 row in set (0.00 sec)

大小写转换:UPPER(str),UCASE(str) 将小写转换成大写

MariaDB [lyshark]> select UPPER('black'),UCASE('mkdirs');
+----------------+-----------------+
| UPPER('black') | UCASE('mkdirs') |
+----------------+-----------------+
| BLACK          | MKDIRS          |
+----------------+-----------------+
1 row in set (0.00 sec)

比较字符串大小:STRCMP(s1,s2) 相同返回0,s1<s2返回-1,其他返回1

MariaDB [lyshark]> select STRCMP('lyshark','lyshark'),STRCMP('txt','ttxt'),STRCMP('ttxt','txt');
+-----------------------------+----------------------+----------------------+
| STRCMP('lyshark','lyshark') | STRCMP('txt','ttxt') | STRCMP('ttxt','txt') |
+-----------------------------+----------------------+----------------------+
|                           0 |                    1 |                   -1 |
+-----------------------------+----------------------+----------------------+
1 row in set (0.00 sec)

字符串逆序:REVERSE(str)

MariaDB [lyshark]> select REVERSE('lyshark');
+--------------------+
| REVERSE('lyshark') |
+--------------------+
| krahsyl            |
+--------------------+
1 row in set (0.00 sec)

◆日期时间函数◆

获取当前日期:CURDATE()

MariaDB [lyshark]> select CURDATE(),CURRENT_DATE(),CURDATE()+1;
+------------+----------------+-------------+
| CURDATE()  | CURRENT_DATE() | CURDATE()+1 |
+------------+----------------+-------------+
| 2018-12-24 | 2018-12-24     |    20181225 |
+------------+----------------+-------------+
1 row in set (0.00 sec)

获取当前时间:CURTIME()

MariaDB [lyshark]> select CURTIME(),CURRENT_TIME(),CURTIME()+1;
+-----------+----------------+-------------+
| CURTIME() | CURRENT_TIME() | CURTIME()+1 |
+-----------+----------------+-------------+
| 20:49:04  | 20:49:04       |      204905 |
+-----------+----------------+-------------+
1 row in set (0.00 sec)

获取日期与时间:ALL

MariaDB [lyshark]> select CURRENT_TIMESTAMP(),LOCALTIME(),NOW(),SYSDATE();
+---------------------+---------------------+---------------------+---------------------+
| CURRENT_TIMESTAMP() | LOCALTIME()         | NOW()               | SYSDATE()           |
+---------------------+---------------------+---------------------+---------------------+
| 2018-12-24 20:50:19 | 2018-12-24 20:50:19 | 2018-12-24 20:50:19 | 2018-12-24 20:50:19 |
+---------------------+---------------------+---------------------+---------------------+
1 row in set (0.00 sec)

获取UNIX时间戳:UNIX_TIMESTAMP()

MariaDB [lyshark]> select UNIX_TIMESTAMP(),UNIX_TIMESTAMP(NOW()),NOW();
+------------------+-----------------------+---------------------+
| UNIX_TIMESTAMP() | UNIX_TIMESTAMP(NOW()) | NOW()               |
+------------------+-----------------------+---------------------+
|       1545702698 |            1545702698 | 2018-12-24 20:51:38 |
+------------------+-----------------------+---------------------+
1 row in set (0.00 sec)

获取年份:YEAR()

MariaDB [lyshark]> select year('18-10-10');
+------------------+
| year('18-10-10') |
+------------------+
|             2018 |
+------------------+
1 row in set (0.00 sec)

获取月份:MONTH()

MariaDB [lyshark]> select month('2018-10-05');
+---------------------+
| month('2018-10-05') |
+---------------------+
|                  10 |
+---------------------+
1 row in set (0.00 sec)

获取星期:DAYNAME()

MariaDB [lyshark]> select dayname('2018-10-25');
+-----------------------+
| dayname('2018-10-25') |
+-----------------------+
| Thursday              |
+-----------------------+
1 row in set (0.00 sec)

获取天:DAYOFYEAR()

MariaDB [lyshark]> select dayofyear('2018-10-10');
+-------------------------+
| dayofyear('2018-10-10') |
+-------------------------+
|                     283 |
+-------------------------+
1 row in set (0.00 sec)

◆条件判断函数◆

IF(expr,v1,v2): 如果表达式expr是true(expr<>0 and expr<> NULL),则if()函数返回为v1,否则返回v2,if()语句返回值为数字或字符串,具体情况视其所在语境而定.

MariaDB [lyshark]> select if(1>2,2,3),
    -> if(1<2,'yes','no'),
    -> if(strcmp('test','test1'),'no','yes');

+-------------+--------------------+---------------------------------------+
| if(1>2,2,3) | if(1<2,'yes','no') | if(strcmp('test','test1'),'no','yes') |
+-------------+--------------------+---------------------------------------+
|           3 | yes                | no                                    |
+-------------+--------------------+---------------------------------------+
1 row in set (0.00 sec)

IFNULL(v1,v2): 假如v1不为null,则ifnull()返回值为v1,否则其返回值为v2.

MariaDB [lyshark]> select ifnull(1,2) , ifnull(null,10) , ifnull(1/0,'wrong');
+-------------+-----------------+---------------------+
| ifnull(1,2) | ifnull(null,10) | ifnull(1/0,'wrong') |
+-------------+-----------------+---------------------+
|           1 |              10 | wrong               |
+-------------+-----------------+---------------------+
1 row in set (0.00 sec)

case expr when v1 then r1 [when v2 then r2][else rn] end: 如果expr等价于某个vn,则返回对应位置then后面的结果.如果所用值都不相等,则返回else后面的rn.

MariaDB [lyshark]> select case 2 when 1 then 'one' when 2 then 'two' else 'more' end;
+------------------------------------------------------------+
| case 2 when 1 then 'one' when 2 then 'two' else 'more' end |
+------------------------------------------------------------+
| two                                                        |
+------------------------------------------------------------+
1 row in set (0.00 sec)


MariaDB [lyshark]> select case when 1<0 then 'true' else 'false' end;
+--------------------------------------------+
| case when 1<0 then 'true' else 'false' end |
+--------------------------------------------+
| false                                      |
+--------------------------------------------+
1 row in set (0.00 sec)

◆系统信息函数◆

获取版本:version()

MariaDB [lyshark]> select version();
+----------------+
| version()      |
+----------------+
| 5.5.60-MariaDB |
+----------------+
1 row in set (0.04 sec)

查看当前用户连接数:connection_id()

MariaDB [lyshark]> select connection_id();
+-----------------+
| connection_id() |
+-----------------+
|               2 |
+-----------------+
1 row in set (0.00 sec)

输出当前用户的连接信息:show processlist

MariaDB [lyshark]> show processlist;
+----+------+-----------+---------+---------+------+-------+------------------+----------+
| Id | User | Host      | db      | Command | Time | State | Info             | Progress |
+----+------+-----------+---------+---------+------+-------+------------------+----------+
|  2 | root | localhost | lyshark | Query   |    0 | NULL  | show processlist |    0.000 |
+----+------+-----------+---------+---------+------+-------+------------------+----------+
1 row in set (0.01 sec)

MariaDB [lyshark]>
MariaDB [lyshark]> show full processlist;
+----+------+-----------+---------+---------+------+-------+-----------------------+----------+
| Id | User | Host      | db      | Command | Time | State | Info                  | Progress |
+----+------+-----------+---------+---------+------+-------+-----------------------+----------+
|  2 | root | localhost | lyshark | Query   |    0 | NULL  | show full processlist |    0.000 |
+----+------+-----------+---------+---------+------+-------+-----------------------+----------+
1 row in set (0.00 sec)

返回当前使用的数据库:schema()

MariaDB [lyshark]> select database(),schema();
+------------+----------+
| database() | schema() |
+------------+----------+
| lyshark    | lyshark  |
+------------+----------+
1 row in set (0.00 sec)

◆加密解密函数◆

加密函数:password(str)

MariaDB [lyshark]> select password('newpass');
+-------------------------------------------+
| password('newpass')                       |
+-------------------------------------------+
| *D8DECEC305209EEFEC43008E1D420E1AA06B19E0 |
+-------------------------------------------+
1 row in set (0.00 sec)

加密函数:MD5(str)

MariaDB [lyshark]> select MD5('mypass');
+----------------------------------+
| MD5('mypass')                    |
+----------------------------------+
| a029d0df84eb5549c641e04a9ef389e5 |
+----------------------------------+
1 row in set (0.00 sec)

加密函数:encode(str,pswd_str)

MariaDB [lyshark]> select encode('secret','cry'),length(encode('secret','cry'));
+------------------------+--------------------------------+
| encode('secret','cry') | length(encode('secret','cry')) |
+------------------------+--------------------------------+
| ▒h▒ ▒                  |                              6 |
+------------------------+--------------------------------+
1 row in set (0.00 sec)

解密函数:decode(crypt_str,pswd_str)

MariaDB [lyshark]> select decode(encode('secret','cry'),'cry');
+--------------------------------------+
| decode(encode('secret','cry'),'cry') |
+--------------------------------------+
| secret                               |
+--------------------------------------+
1 row in set (0.00 sec)

◆其他通用函数◆

格式化函数:ormat(x,n)

MariaDB [lyshark]> select format(123.123,2);
+-------------------+
| format(123.123,2) |
+-------------------+
| 123.12            |
+-------------------+
1 row in set (0.00 sec)

IP地址转为数字:inet_aton(ipaddr)

MariaDB [lyshark]> select inet_aton("192.168.1.1");
+--------------------------+
| inet_aton("192.168.1.1") |
+--------------------------+
|               3232235777 |
+--------------------------+
1 row in set (0.00 sec)

数字转为IP地址:inet_ntoa

MariaDB [lyshark]> select inet_ntoa(3232235777);
+-----------------------+
| inet_ntoa(3232235777) |
+-----------------------+
| 192.168.1.1           |
+-----------------------+
1 row in set (0.00 sec)