MySQL database order by is extremely slow

I ran into a weird problem today.

There is a large amount of sql data, such as where and order by. Without order by, the speed is very fast, and if it is added, it is very slow.

 

1. First, we execute the query plan on this sql:

explain select t.order_id from book_order t  ORDER BY t.order_id desc

 

 

explain select t.order_id from book_order t

 

 

 

 

The index applied by this statement is idx_bo_order_book_local

 

 

After further confirmation, after using the where condition, the index becomes the primary key.

explain select t.order_id from book_order t where t.order_id = 1593539

 

 

From the above it can be seen that:

MySQL's default query (without the where condition) does not necessarily use the primary key. Since each simple query in MySQL only applies one index, the order by primary key is used at this time, and the indexing function of the primary key is invalid.

 

Two: the solution

1. Order by index (the index referenced in the where condition).

2. Force the use of the primary key: FORCE INDEX (PRI), if you want to force the use of an index, use FORCE INDEX (index name).

explain select t.order_id from book_order t FORCE INDEX(idx_bo_order_book_local) ORDER BY t.order_id desc;

 

 3. Analysis of the reasons for the failure of other order by indexes

 

1. MySQL only applies one index to a simple statement every day, so the field of order by must be in the index, and it can be combined with the where condition to form a composite index.

 

2. The field of select must be an index field. (except for primary key queries)

 

3. If the sql statement is a compound statement, including sub-queries, etc., the statement can be decomposed into simple queries for analysis.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325645908&siteId=291194637