First there is a user_info table with an id field. Execute the following query statement:
select * from user_info where id = 1;
The return result is:
Mysql basic architecture diagram:
(Related video tutorial recommendations: mysql video tutorial)
Generally speaking, MySQL is divided into two parts: Server layer and storage engine layer.
The Server layer includes connectors, query caches, analyzers, executors, etc., as well as all built-in functions (such as date, time, math and encryption functions, etc.) and cross-storage engine functions (such as stored procedures, triggers, views).
The storage engine layer is responsible for data storage and retrieval, and supports multiple storage engines such as InnoDB, MyISAM, and Memory. The default storage engine after MySQL 5.5.5 is InnoDB.
Connector
Before querying SQL statements, you must first establish a connection with MySQL, which is done by the connector. The connector is responsible for establishing a connection with the client, obtaining permissions, maintaining and managing the connection. The connection command is:
mysql -h$ip -P$port -u$user -p
Enter the password. After the verification is passed, the connector will go to the permission table to find out the permissions you have. Afterwards, the permission judgment logic in this connection will depend on what is read at this time. Permissions. After a user successfully establishes a connection, even if the administrator modifies the user's permissions, it will not affect the permissions of the existing connection. After the modification, only new connections will use the new permission settings.
After the connection is completed, if you have no subsequent actions, the connection will be in an idle state. You can see it in the show processlist command. The results are as follows:
If the client is inactive for too long, the connector will automatically disconnect it; this time is controlled by the parameter wait_timeout, and the default value is 8 Hour. If the client sends a request again after the connection is disconnected, it will receive an error reminder: Lost connection to MySQL server during query
Long connection And short connection
#In the database, a long connection means that after the connection is successful, if the client continues to make requests, the same connection will always be used. A short connection means that the connection is disconnected after a few queries are executed, and a new one is re-established for the next query.
The process of establishing a connection is usually complicated. It is recommended to minimize the actions of establishing a connection during use and try to use long connections. However, after all long connections are used, sometimes the memory occupied by MySQL increases very quickly. This is because the memory temporarily used by MySQL during execution is managed in the connection object.
These resources will be released when the connection is disconnected. Therefore, if long connections accumulate, they may occupy too much memory and be forcibly killed by the system (OOM). Judging from the phenomenon, MySQL restarts abnormally.
How to solve this problem? You can consider the following two solutions:
Disconnect long connections regularly. After using it for a period of time, or after the program determines that a large query that takes up memory has been executed, the connection is disconnected, and then the query is required and then reconnected. For MySQL 5.7 and above, you can reinitialize the connection resource by executing mysql_reset_connection after each execution of a relatively large operation. This process does not require reconnection and permission verification, but will restore the connection to the state when it was just created.
Query Cache
After the connection is established, the select statement begins to be executed. The cache will be queried first before execution.
After MySQL gets the query request, it will first query the cache to see if this statement has been executed. The executed statements and their results will be stored in a certain memory area in the form of key-value pairs. The key is the query statement, and the value is the query result. If your query can find the key directly in this cache, then the
value will be returned directly to the client.
If the statement is not in the query cache, the subsequent execution phase will continue. After the execution is completed, the execution results will be stored in the query cache. If the query hits the cache, MySQL can directly return the results without performing subsequent complex operations, which will improve efficiency.
但是查询缓存的失效非常频繁,只要有对一个表的更新,这个表上所有的查询缓存都会被清空。对于更新压力大的数据库来说,查询缓存的命中率会非常低。如果业务中需要有一张静态表,很长时间才会更新一次。
比如,一个系统配置表,那这张表上的查询才适合使用查询缓存。MySQL 提供了这种按需使用的方式。可以将参数 query_cache_type 设置成 DEMAND,对于默认的 SQL 语句都将不使用查询缓存。而对于你确定要使用查询缓存的语句,可以用 SQL_CACHE 显式指定,如下:
mysql> select SQL_CACHE * from user_info where id = 1;
MySQL 8.0 版本将查询缓存的功能删除了。
分析器(Analyzer)
如果查询缓存未命中,就要开始执行语句了。首先,MySQL 需要对 SQL 语句进行解析。
分析器先会做词法分析。SQL 语句是由多个字符串和空格组成的,MySQL 需要识别出里面的字符串分别是什么,代表什么。MySQL 从你输入的 select 这个关键字识别出来,这是查询语句。它也要把字符串 user_info 识别成表名,把字符串 id 识别成列名。之后就要做语法分析。根据词法分析的结果,语法分析器会根据语法规则,判断输入的 SQL 语句是否满足 MySQL 语法。
如果你 SQL 语句不对,就会收到 You have an error in your SQL syntax 的错误提醒,比如下面这个语句 from 写成了 form。
mysql> select * form user_info where id = 1; 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'form user_info where id = 1' at line 1
一般语法错误会提示第一个出现错误的位置,所以要关注的是紧接 use near 的内容。
优化器(Optimizer)
经过分析器的词法分析和语法分析后,还要经过优化器的处理。
优化器是在表里面有多个索引的时候,决定使用哪个索引;或者在一个语句有多表关联(join)的时候,决定各个表的连接顺序。比如你执行下面这样的语句,这个语句是执行两个表的 join:
mysql> SELECT * FROM order_master JOIN order_detail USING (order_id) WHERE order_master.pay_status = 0 AND order_detail.detail_id = 1558963262141624521;
既可以先从表 order_master 里面取出 pay_status = 0 的记录的 order_id 值,再根据 order_id 值关联到表 order_detail,再判断 order_detail 里面 detail_id 的值是否等于 1558963262141624521。
也可以先从表 order_detail 里面取出 detail_id = 1558963262141624521 的记录的 order_id 值,再根据 order_id 值关联到 order_master,再判断 order_master 里面 pay_status 的值是否等于 0。
这两种执行方法的逻辑结果是一样的,但是执行的效率会有不同,而优化器的作用就是决定选择使用哪一个方案。优化器阶段完成后,这个语句的执行方案就确定下来了,然后进入执行器阶段。
执行器(Actuator)
MySQL 通过分析器知道了要做什么,通过优化器知道了该怎么做,于是就进入了执行器阶段,开始执行语句。
开始执行的时候,要先判断一下你对这个表 user_info 有没有执行查询的权限,如果没有,就会返回没有权限的错误,如下所示 (如果命中查询缓存,会在查询缓存返回结果的时候,做权限验证。查询也会在优化器之前调用 precheck 验证权限)。
mysql> select * from user_info where id = 1;ERROR 1142 (42000): SELECT command denied to user 'wupx'@'localhost' for table 'user_info'
如果有权限,就打开表继续执行。打开表的时候,执行器就会根据表的引擎定义,去使用这个引擎提供的接口。比如我们这个例子中的表 user_info 中,id 字段没有索引,那么执行器的执行流程是这样的:
1、调用 InnoDB 引擎接口取这个表的第一行,判断 id 值是不是 1,如果不是则跳过,如果是则将这行存在结果集中;
2、调用引擎接口取下一行,重复相同的判断逻辑,直到取到这个表的最后一行。
3、执行器将上述遍历过程中所有满足条件的行组成的记录集作为结果集返回给客户端。
对于有索引的表,第一次调用的是取满足条件的第一行这个接口,之后循环取满足条件的下一行这个接口。
数据库的慢查询日志中有 rows_examined 字段,表示这个语句执行过程中扫描了多少行。这个值就是在执行器每次调用引擎获取数据行的时候累加的。在有些场景下,执行器调用一次,在引擎内部则扫描了多行,因此引擎扫描行数跟 rows_examined 并不是完全相同的。
总结
主要通过对一个 SQL 语句完整执行过程进行讲解,介绍 MySQL 的逻辑架构,MySQL 主要包括连接器、查询缓存、分析器、优化器、执行器这几个模块。
相关文章教程推荐:mysql教程
The above is the detailed content of Analyze how SQL query statements are executed. For more information, please follow other related articles on the PHP Chinese website!