MySQL query in simple terms

Query execution process

The MySQL query process is generally divided into five steps:

  1. Send a query request to the MySQL server;
  2. The server first checks the query cache, and if it hits the cache, it will immediately return the data stored in the cache, otherwise it will enter the next stage;
  3. The service parses and preprocesses the SQL, and then the optimizer generates the corresponding execution plan;
  4. MySQL calls the storage engine API to execute the query according to the execution plan;
  5. Return the result to the client and cache the query result at the same time.

query cache

The additional consumption of the query cache on the system is not only in the write operation, but also in the read operation:

  1. Any query statement must be checked before starting, even if this SQL will not hit the query cache;
  2. Two identical SQL statements, one of which is due to uppercase letters and extra spaces, will not be hit when querying the cache, so when we write SQL statements in the specification, both uppercase and lowercase should be used;
  3. If the query result can be cached, the result will be cached after the execution is completed, but it will also bring additional consumption to the system;
  4. If the data in the table related to the cached result is changed, the cached result will be invalidated;

query optimizer

MySQL's query optimizer is a very complex component, which uses a lot of optimization strategies to generate an optimal execution plan, such as:

  1. Redefine the association order of tables (when multiple tables are associated with queries, it does not necessarily follow the order specified in SQL, but there are some techniques to specify the association order);
  2. Optimize the MIN() and MAX() functions (to find the minimum value of a column, if the column has an index, you only need to find the leftmost end of the B+Tree index, otherwise you can find the maximum value);
  3. Terminate the query early (for example: when using LIMIT, the query will be terminated immediately after finding a sufficient number of result sets);
  4. Optimized sorting (in the old version of MySQL, two transmission sorts are used, that is, the row pointer and the field to be sorted are first read and sorted in memory, and then the data row is read according to the sorting result, while the new version uses a single One-transfer sorting, that is, reading all data rows at one time, and then sorting them according to a given column. For I/O-intensive applications, the efficiency will be much higher).

Guess you like

Origin blog.csdn.net/qq_44726330/article/details/121831130