Optimize query performance optimization -Limit

5, Limit query optimization

Limit commonly used in the paging process, accompanied by long order by clause to use, so most of the time back to using Filesorts this will cause a lot of IO issues.
Examples:
Demand: query video id and description, and sorted according to topic, extracted five data starting from the number 50.

select film_id,description from sakila.film order by title limit 50,5;

Implementation of the results:
Here Insert Picture Description
In a look at its implementation plan:
Here Insert Picture Description
For this operation, we kind of optimizations used?
Optimization Step 1:
using an indexed primary key column or order by operation, because we know, is InnoDB logical order ordered by the primary key. You can avoid a lot of IO operations.

select film_id,description from sakila.film order by film_id limit 50,5;

Here Insert Picture Description
Look at the execution plan
Here Insert Picture Description
that if we get the five records began 500 lines, the implementation plan is what the?

explain select film_id,description from sakila.film order by film_id limit 500,5\G

Here Insert Picture Description
Here Insert Picture Description
As we flip the future, IO operations will become increasingly large, if a table has tens of millions of rows of data, flip the back, will be more and more slowly, so we have to be further optimized.

Optimization Step 2
record in the primary key returned by the last used the next time the primary key query filtration. (Note: to avoid excessive scanning of large volumes of data recording)
last operating limit is 50, 5, and therefore we need in this optimization process using the previous record index value,

select film_id,description from sakila.film  where film_id >55 and film_id<=60 order by film_id limit 1,5;

View the execution plan:
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Conclusion: The same number of scan lines, the implementation plan is fixed, the efficiency is very fixed

Note:
the primary key to sort order and continuous, if the primary key intermediate vacant for a column, or a few columns will be insufficient data lists the data five lines appear; if not continuous, the establishment of an additional column index_id column, guarantee the column data to be auto-incremented, and add to the index.

Released 1079 original articles · won praise 888 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_42528266/article/details/103993809