MySQL的变量分类总结

 

在MySQL中,my.cnf是参数文件(Option Files),相似于ORACLE数据库中的spfile、pfile参数文件,照理说,参数文件my.cnf中的都是系统参数(这种称呼比较符合思惟习惯),可是官方又称呼其为系统变量(system variables),那么到底这个叫系统参数或系统变量(system variables)呢? 这个曾经是一个让我很纠结的问题,由于MySQL中有各类类型的变量,有时候语言就是这么博大精深;相信不少人也对这个问题或多或少有点困惑。其实抛开这些名词,它们就是同一个事情(东西),无论你叫它系统变量(system variables)或系统参数均可,无需那么纠结。 就比如王三,有人叫他王三;也有人也叫他王麻子绰号同样。html

 

另外,MySQL中有不少变量类型,确实有时候让人有点混淆不清,本文打算总结一下MySQL数据库的各类变量类型,理清各类变量类型概念。可以从全局有个清晰思路。MySQL变量类型具体参考下图:mysql

 

clip_image001

 

 

 

 

Server System Variables(系统变量)sql

 

 

MySQL系统变量(system variables)是指MySQL实例的各类系统变量,其实是一些系统参数,用于初始化或设定数据库对系统资源的占用,文件存放位置等等,这些变量包含MySQL编译时的参数默认值,或者my.cnf配置文件里配置的参数值。默认状况下系统变量都是小写字母。官方文档介绍以下:数据库

 

The MySQL server maintains many system variables that indicate how it is configured. Each system variable has a default value. System variables can be set at server startup using options on the command line or in an option file. Most of them can be changed dynamically at runtime using the SET statement, which enables you to modify operation of the server without having to stop and restart it. You can also use system variable values in expressions.express

 

 

系统变量(system variables)按做用域范围能够分为会话级别系统变量和全局级别系统变量。若是要确认系统变量是全局级别仍是会话级别,能够参考官方文档,若是Scope其值为GLOBAL或SESSION,表示变量既是全局级别系统变量,又是会话级别系统变量。若是其Scope其值为GLOBAL,表示系统变量为全局级别系统变量。c#

 

--查看系统变量的全局值服务器

 

select * from information_schema.global_variables;session

select * from information_schema.global_variablesapp

  where variable_name='xxxx';ide

select * from performance_schema.global_variables;

 

 

--查看系统变量的当前会话值

 

select * from information_schema.session_variables;

    select * from information_schema.session_variables

  where variable_name='xxxx';

select * from performance_schema.session_variables;

 

 

 

 

SELECT @@global.sql_mode, @@session.sql_mode, @@sql_mode;

 

mysql> show variables like '%connect_timeout%'; 

mysql> show local variables like '%connect_timeout%';

mysql> show session variables like '%connect_timeout%';

mysql> show global variables like '%connect_timeout%';

 

注意:对于SHOW VARIABLES,若是不指定GLOBAL、SESSION或者LOCAL,MySQL返回SESSION值,若是要区分系统变量是全局仍是会话级别。不能使用下面方式,若是某一个系统变量是全局级别的,那么在当前会话的值也是全局级别的值。例如系统变量AUTOMATIC_SP_PRIVILEGES,它是一个全局级别系统变量,可是 show session variables like '%automatic_sp_privileges%'同样能查到其值。因此这种方式没法区别系统变量是会话级别仍是全局级别。

 

mysql> show session variables like '%automatic_sp_privileges%';
+-------------------------+-------+
| Variable_name           | Value |
+-------------------------+-------+
| automatic_sp_privileges | ON    |
+-------------------------+-------+
1 row in set (0.00 sec)
 
mysql> select * from information_schema.global_variables
    -> where variable_name='automatic_sp_privileges';
+-------------------------+----------------+
| VARIABLE_NAME           | VARIABLE_VALUE |
+-------------------------+----------------+
| AUTOMATIC_SP_PRIVILEGES | ON             |
+-------------------------+----------------+
1 row in set, 1 warning (0.00 sec)
 
mysql> 

 

 

若是要区分系统变量是全局仍是会话级别,能够用下面方式:

 

方法1: 查官方文档中系统变量的Scope属性。

方法2: 使用SET VARIABLE_NAME=xxx; 若是报ERROR 1229 (HY000),则表示该变量为全局,若是不报错,那么证实该系统变量为全局和会话两个级别。

   

 

mysql> SET AUTOMATIC_SP_PRIVILEGES=OFF;
 
ERROR 1229 (HY000): Variable 'automatic_sp_privileges' is a GLOBAL variable and should be set with SET GLOBAL

 

 

 

可使用SET命令修改系统变量的值,以下所示:

 

修改全局级别系统变量:

 

SET GLOBAL max_connections=300;
 
SET @@global.max_connections=300;

 

注意:更改全局变量的值,须要拥有SUPER权限

 

修改会话级别系统变量:

 

   SET @@session.max_join_size=DEFAULT;

  SET max_join_size=DEFAULT;  --默认为会话变量。若是在变量名前没有级别限定符,表示修改会话级变量。

   SET SESSION max_join_size=DEFAULT;

 

若是修改系统全局变量没有指定GLOBAL或@@global的话,就会报Variable 'xxx' is a GLOBAL variable and should be set with SET GLOBAL这类错误。

 

mysql> set max_connections=300;
ERROR 1229 (HY000): Variable 'max_connections' is a GLOBAL variable and should be set with SET GLOBAL
mysql> set global max_connections=300;
Query OK, 0 rows affected (0.00 sec)
 
mysql> 

 

 

 

系统变量(system variables)按是否能够动态修改,能够分为系统动态变量(Dynamic System Variables)和系统静态变量。怎么区分系统变量是动态和静态的呢? 这个只能查看官方文档,系统变量的"Dynamic"属性为Yes,则表示能够动态修改。Dynamic Variable具体能够参考https://dev.mysql.com/doc/refman/5.7/en/dynamic-system-variables.html

 

另外,有些系统变量是只读的,不能修改的。以下所示:

 

mysql>

mysql> set global innodb_version='5.6.21';

ERROR 1238 (HY000): Variable 'innodb_version' is a read only variable

mysql>

 

 

另外,还有一个Structured System Variables概念,其实就是系统变量是一个结构体(Strut),官方介绍以下所示:

 

Structured System Variables

 

A structured variable differs from a regular system variable in two respects:

 

Its value is a structure with components that specify server parameters considered to be closely related.

 

There might be several instances of a given type of structured variable. Each one has a different name and refers to a different resource maintained by the server.

 

 

 

 

Server Status Variables(服务器状态变量)

 

 

MySQL状态变量(Server Status Variables)是当前服务器从启动后累计的一些系统状态信息,例如最大链接数,累计的中断链接等等,主要用于评估当前系统资源的使用状况以进一步分析系统性能而作出相应的调整决策。这个估计有人会跟系统变量混淆,其实状态变量是动态变化的,另外,状态变量是只读的:只能由MySQL服务器自己设置和修改,对于用户来讲是只读的,不能够经过SET语句设置和修改它们,而系统变量则能够随时修改。状态变量也分为会话级与全局级别状态信息。有些状态变量能够用FLUSH STATUS语句重置为零值。

 

关于查看状态变量,show status也支持like匹配查询。以下所示:

 

show status like '%variable_name%'

show global status like '%variable_name%'

 

  

#当前测试环境
ysql> select version() from dual;
-----------+
 version() |
-----------+
 5.7.21    |
-----------+
 row in set (0.00 sec)
   
mysql> show status;  --查看全部的状态变量
 
 
 
ysql> show global status like 'Aborted_connects%';
------------------+-------+
 Variable_name    | Value |
------------------+-------+
 Aborted_connects | 2     |
------------------+-------+
 row in set (0.01 sec)
 
ysql> show session status like 'Aborted_connects%';
------------------+-------+
 Variable_name    | Value |
------------------+-------+
 Aborted_connects | 2     |
------------------+-------+
 row in set (0.00 sec)
 
ysql> select * from information_schema.global_status;
RROR 3167 (HY000): The 'INFORMATION_SCHEMA.GLOBAL_STATUS' feature is disabled; see the documentation for 'show_compatibility_56'
ysql> #
ysql> show variables like '%show_compatibility_56%';
-----------------------+-------+
 Variable_name         | Value |
-----------------------+-------+
 show_compatibility_56 | OFF   |
-----------------------+-------+
 row in set (0.00 sec)
 
ysql> set global show_compatibility_56=on;
uery OK, 0 rows affected (0.00 sec)
 
ysql> select * from information_schema.global_status;
-----------------------------------------------+---------------------------------------+
 VARIABLE_NAME                                  VARIABLE_VALUE                         |
-----------------------------------------------+---------------------------------------+
 ABORTED_CLIENTS                               | 138097                                |
 ABORTED_CONNECTS                              | 5                                     |
 BINLOG_CACHE_DISK_USE                         | 0                                     |
 BINLOG_CACHE_USE                              | 0                                     |
....................................................................................
 
 
 
select * from performance_schema.global_status;
select * from performance_schema.session_status;

 

 

注意:MySQL 5.7之后系统变量和状态变量须要从performance_schema中进行获取,information_schema仍然保留了GLOBAL_STATUS,GLOBAL_VARIABLES两个表作兼容,若是但愿沿用information_schema中进行查询的习惯,5.7提供了show_compatibility_56参数,设置为ON能够兼容5.7以前的用法,不然就会报错(ERROR 3167 (HY000)).

 

 

 

 

User-Defined Variables(用户自定义变量)

 

 

用户自定义变量,顾名思义就是用户本身定义的变量。用户自定义变量是基于当前会话的。 也就是说用户自定义变量的做用域局限于当前会话(链接),由一个客户端定义的用户自定义变量不能被其余客户端看到或使用。(例外:能够访问performance_schema.user_variables_by_thread表的用户能够看到全部会话的定义的用户自定义变量,固然仅仅能看到那些会话定义了哪些变量,而不能访问这些变量。)。当客户端会话退出时,当前会话全部的自定义变量都会自动释放。

通常能够在SQL语句将值存储在用户自定义变量中,而后再利用另外一条SQL语句来查询用户自定义变量。这样以来,能够在不一样的SQL间传递值。

 

另外,用户自定义变量是大小写不敏感的,最大长度为64个字符,用户自定义变量的形式通常为@var_name,其中变量名称由字母、数字、._$组成。固然,在以字符串或者标识符引用时也能够包含其余特殊字符(例如:@'my-var',@"my-var",或者@`my-var`)。。使用SET设置变量时,可使用=或者:=操做符进行赋值。对于SET,可使用=或:=来赋值,对于SELECT只能使用:=来赋值。以下所示:

 

   

mysql> set @$test1="test";
Query OK, 0 rows affected (0.00 sec)
mysql> select @$test1 from dual;
+---------+
| @$test1 |
+---------+
| test    |
+---------+
1 row in set (0.00 sec)
 
mysql> 
mysql> set @"ac#k":='kerry';
Query OK, 0 rows affected (0.00 sec)
 
mysql> select @"ac#k" from dual;
+---------+
| @"ac#k" |
+---------+
| kerry   |
+---------+
1 row in set (0.00 sec)
 
mysql> 
 
 
mysql> select version() from dual;
+-----------+
| version() |
+-----------+
| 5.7.21    |
+-----------+
1 row in set (0.00 sec)
 
mysql> 
mysql> set @my_test=1200;
Query OK, 0 rows affected (0.00 sec)
 
mysql> select @my_test;
+----------+
| @my_test |
+----------+
|     1200 |
+----------+
1 row in set (0.00 sec)
 
mysql> select connection_id() from dual;
+-----------------+
| connection_id() |
+-----------------+
|          149379 |
+-----------------+
1 row in set (0.00 sec)
 
mysql> SELECT c.id, 
    ->        b.thread_id
    -> FROM   performance_schema.threads b 
    ->     join information_schema.processlist c 
    ->          ON b.processlist_id = c.id 
    -> where c.id=149379;
+--------+-----------+
| id     | thread_id |
+--------+-----------+
| 149379 |    149404 |
+--------+-----------+
1 row in set (0.00 sec)
 
mysql> select @My_Test, @my_TEST from dual;
+----------+----------+
| @My_Test | @my_TEST |
+----------+----------+
|     1200 |     1200 |
+----------+----------+
1 row in set (0.00 sec)
 
mysql> 

 

 

 clip_image002

 

 

mysql> select connection_id() from dual;
+-----------------+
| connection_id() |
+-----------------+
|          151821 |
+-----------------+
1 row in set (0.00 sec)
 
mysql> select @my_test from dual;
+----------+
| @my_test |
+----------+
| NULL     |
+----------+
1 row in set (0.00 sec)
 
mysql> select * from performance_schema.user_variables_by_thread;
+-----------+---------------+----------------+
| THREAD_ID | VARIABLE_NAME | VARIABLE_VALUE |
+-----------+---------------+----------------+
|    149404 | my_test       | 1200           |
+-----------+---------------+----------------+
1 row in set (0.00 sec)
 
mysql> 

 

 

clip_image003

 

 

 

用户自定义变量注意事项,如下为总结:

 

1:未定义的用户自定义变量初始值是NULL

 

mysql> select @kerry from dual;
 
+--------+
 
| @kerry |
 
+--------+
 
| NULL   |
 
+--------+
 
1 row in set (0.00 sec)

 

注意:使用未定义变量不会产生任何语法错误,因为其被初始化为NULL值,若是没有意识到这一点,很是容易犯错。以下所示:

 

mysql> select @num1, @num2 :=@num1+1 from dual;
+-------+-----------------+
| @num1 | @num2 :=@num1+1 |
+-------+-----------------+
| NULL  |            NULL |
+-------+-----------------+
1 row in set (0.00 sec)
 
mysql>

 

 

 

2:用户变量名对大小写不敏感(上面已经叙述,此处从略)

 

3:自定义变量的类型是一个动态类型。

 

MySQL中用户自定义变量,不严格限制数据类型的,它的数据类型根据你赋给它的值而随时变化。并且自定义变量若是赋予数字值,是不能保证进度的。官方文档介绍:

 

User variables can be assigned a value from a limited set of data types: integer, decimal, floating-point, binary or nonbinary string, or NULL value. Assignment of decimal and real values does not preserve the precision or scale of the value. A value of a type other than one of the permissible types is converted to a permissible type. For example, a value having a temporal or spatial data type is converted to a binary string. A value having the JSON data type is converted to a string with a character set of utf8mb4 and a collation of utf8mb4_bin.

 

 

 

4:赋值的顺序和赋值的时间点并不老是固定的,这依赖于优化器的决定。

 

 

使用用户自定义变量的一个最多见的问题就是没有注意到在赋值和读取用户自定义变量的时候多是在查询的不一样阶段。例如,在SELECT语句中进行赋值而后再WHERE子句中读取用户自定义变量,则可能用户自定义变量取值并不不是你所想象的那样,以下例子所示,由于按照MySQL语句的执行顺序,WHERE部分优先与SELECT部分操做,因此你会看到msgid 和 @rownum的最大值为6.

 

mysql> select msgid from message order by msgid limit 12;
+-------+
| msgid |
+-------+
|     1 |
|     2 |
|     3 |
|     4 |
|     5 |
|     6 |
|     7 |
|    11 |
|    12 |
|    13 |
|    18 |
|    19 |
+-------+
12 rows in set (0.00 sec)
 
mysql> set @rownum := 0;
Query OK, 0 rows affected (0.00 sec)
 
mysql> select msgid , @rownum := @rownum +1 as rownum
    -> from message
    -> where @rownum <=5;
+-------+--------+
| msgid | rownum |
+-------+--------+
|     1 |      1 |
|     2 |      2 |
|     3 |      3 |
|     4 |      4 |
|     5 |      5 |
|     6 |      6 |
+-------+--------+
6 rows in set (0.00 sec)
 
mysql> select msgid , @rownum := @rownum +1 as rownum
    -> from message
    -> where @rownum <=5;
Empty set (0.00 sec)
 
mysql> select @rownum from dual;
+---------+
| @rownum |
+---------+
|       6 |
+---------+
1 row in set (0.00 sec)
 
mysql> 

 

clip_image004

 

如上所示,第二次查询可能你想要的逻辑跟实际逻辑已经出现了误差,这个是使用自定义变量须要当心的地方。由于用户自定义变量在当前会话中也算一个全局变量,它已经变成了6,where条件后面的 @rownum <= 5 逻辑为false了。一不小当心就会出现和你预想的结果出现误差。

 

 

不要在同一个非SET语句中同时赋值并使用同一个用户自定义变量,由于WHERE和SELECT是在查询执行的不一样阶段被执行的。若是在查询中再加入ORDER BY的话,结果可能会更不一样;

 

mysql> set @rownum :=0;
Query OK, 0 rows affected (0.00 sec)
 
mysql> select msgid , @rownum := @rownum +1 as rownum
    -> from message
    -> where @rownum <=5;
+-------+--------+
| msgid | rownum |
+-------+--------+
|     1 |      1 |
|     2 |      2 |
|     3 |      3 |
|     4 |      4 |
|     5 |      5 |
|     6 |      6 |
+-------+--------+
6 rows in set (0.00 sec)
 
mysql> 
 
 
 
mysql> set @rownum := 0;
Query OK, 0 rows affected (0.00 sec)
 
mysql> select msgid, @rownum := @rownum +1 as rownum
    -> from message
    -> where @rownum <=5
    -> order by msgcontent;
+-------+--------+
| msgid | rownum |
+-------+--------+
|    20 |      1 |
|    28 |      2 |
|    43 |      3 |
|    47 |      4 |
..................
..................
|    22 |     57 |
|    69 |     58 |
|    40 |     59 |
|    52 |     60 |
|    24 |     61 |
|    66 |     62 |
|    51 |     63 |
+-------+--------+
63 rows in set (0.00 sec)
 
mysql> 

 

clip_image005

 

 

若是按msgid排序,那么又是正常的,那三者有啥区别呢?

 

mysql> set @rownum :=0;
Query OK, 0 rows affected (0.00 sec)
 
mysql> select msgid, @rownum := @rownum +1 as rownum
    -> from message
    -> where @rownum <=5
    -> order by msgid;
+-------+--------+
| msgid | rownum |
+-------+--------+
|     1 |      1 |
|     2 |      2 |
|     3 |      3 |
|     4 |      4 |
|     5 |      5 |
|     6 |      6 |
+-------+--------+
6 rows in set (0.00 sec)
 
mysql> 

 

咱们先看执行计划

 

image

 

官方的解释以下:

 

In a SELECT statement, each select expression is evaluated only when sent to the client. This means that in a HAVING, GROUP BY, or ORDER BY clause, referring to a variable that is assigned a value in the select expression list does not work as expected

 

在SELECT语句中,每一个选择表达式仅在发送给客户端时才被计算。 这意味着在HAVING,GROUP BY或ORDER BY子句中,引用在选择表达式列表中指定值的用户自定义变量不能按预期工做。 也就是说用户自定义变量的值是在结果集发送到客户端后才计算的

 

测试官方的例子:

 

clip_image006

 

 

clip_image007

 

 

这种解释算是比较权威的,可是,让人有点不解的是,SQL执行顺序中WHERE在SELECT操做以前, 可是第一个SQL语句又怎么解释呢?有种解释是MySQL优化器在某些场景下可能会将这些变量优化掉,这可能致使代码不按预想的方式运行。 解决这个问题的办法是让变量的赋值和取值发生在执行查询的同一阶段,以下所示:

 

clip_image008

 

 

 

 

关于用户自定义变量,若是运用的好,可以写出高效简洁的SQL语句,若是运用不当,也可能把本身给坑了。这个彻底取决于使用它的人。

 

官方文档也有介绍用户自定义变量不适合使用场景。摘抄部分以下:

 

User variables may be used in most contexts where expressions are permitted. This does not currently include contexts that explicitly require a literal value, such as in the LIMIT clause of a SELECT statement, or the IGNORE N LINES clause of a LOAD DATA statement.

 

User variables are intended to provide data values. They cannot be used directly in an SQL statement as an identifier or as part of an identifier, such as in contexts where a table or database name is expected, or as a reserved word such as SELECT.

 

 

 

局部变量

 

 

 

局部变量:做用范围在begin到end语句块之间。在该语句块里设置的变量。declare语句专门用于定义声明局部变量。

 

 

局部变量与用户自定义变量的区分在于下面这些方面:

 

1.用户自定义变量是以"@"开头的。局部变量没有这个符号。

 

2.定义变量方式不一样。用户自定义变量使用set语句,局部变量使用declare语句定义

 

3.做用范围不一样。局部变量只在begin-end语句块之间有效。在begin-end语句块运行完以后,局部变量就消失了。而用户自定义变量是对当前链接(会话)有效。

 

 

 

 

 

 

 

参考资料:

 

https://dev.mysql.com/doc/refman/5.7/en/user-variables.html

https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html

https://dev.mysql.com/doc/refman/5.7/en/using-system-variables.html

https://dev.mysql.com/doc/refman/5.7/en/structured-system-variables.html

https://dev.mysql.com/doc/refman/5.7/en/declare-local-variable.html

https://www.jianshu.com/p/357a02fb2d64

相关文章
相关标签/搜索