The index selection strategy of MySQL's actual combat optimizer


Preface


Tip: The following is the content of this article, the following cases are for reference

One, optimizer index selection strategy

Choosing an index is the task of the optimizer, but sometimes the optimizer is not so smart, so the index selection error will occur.

There are many issues that affect the index selection strategy, for example

  • Scan lines
  • Do you need to use a temporary table
  • Is it sorted

Here is a question,

1.How does MySQL judge the number of scanned rows?

MySQL uses index discrimination to determine which index to choose. Index discrimination is actually the number of different values on the index field , that is, how many different values ​​there are. The larger the value, the higher the index discrimination, and the The greater the chance of the optimizer’s selection

? So MySQL is how to get the value of it InnoDB will be selected by default Npages of data, statistics on the number of different values, averaged, and then the data pages of the index multiplied result ; when the number of rows of data changes over 1/Mtime , Will re-statistical discrimination

2. Persistent storage of distinction

MySQL uses innodb_stats_persistentparameters to control whether persistent storage is required. When the parameter value onis, the statistical information will be persistently stored . At this time N==20,M==10, the distinction is stored in the memory.N==8,M==16

Reasons for misjudgment by optimizer

Index discrimination is not the whole reason for the optimizer's misjudgment. The
optimizer will predict the number of scan rows based on the input index discrimination . It is this pre-judgment operation that causes the deviation of index selection.

At the same time , the cost of returning to the table will also be taken into account. The above reasons have caused the optimizer to misjudge.

2. Exceptions in index selection and handling

solution:

  1. Manually select a suitable index
  2. Modify the SQL statement, add other indexes to give the optimizer more choices
  3. Modify the table structure, add a suitable index or delete the misused index

Guess you like

Origin blog.csdn.net/qq_45596525/article/details/115055958