MySQL optimization limit and order by

 

Optimize order by

 

Query the movie id and description information, and sort them according to the theme, and take out 5 pieces of data starting with the serial number 50.

The unoptimized SQL statement is as follows

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

 

We let the order by field be the primary key index, and then look at the execution plan, which greatly improves efficiency

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

 

 

 

Optimize limit

 

Suppose we want to start with a row of hundreds of thousands of millions of data and take 5 records. In this way, the IO operation will become larger and larger, so we need to record the primary key of the last query and use it in the next query Primary key filtering. This avoids scanning too many records when the amount of data is large

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

 You can see this operation, the number of rows retrieved is only 5 lines, whether you start with tens of thousands of data.

k

Note: The primary key should be sorted sequentially and consecutively. If there is a column or columns in the primary key, data with less than 5 rows of data will appear; if it is not continuous, create an additional column index_id column to ensure A column of data should be self-increasing, and add the index

Published 568 original articles · Like 180 · Visits 180,000+

Guess you like

Origin blog.csdn.net/Delicious_Life/article/details/105609778