What if the correct index is not selected by MySQL

1. optimize table
If MySQL does not select the correct index, it may be because the table is frequently changed. This affects statistics. If time permits (the table is locked during this period), we can help solve this problem by rebuilding the table.

For details, please refer to the previous article: mysql optimize table

 

2. Analyze table
analyze table takes less time, especially in InnoDB. The analysis will update the index statistics and help generate a better query plan.

 

3. Use hint

For example, use the keywords use index (index-name), force index (index-name)

select c1 from abce use index(idx_c1)  where ... ;
select c1 from abce force index(idx_c1)  where ... ;

  

4. Ignore the index

If you use the wrong index, you can try to use the keyword to ignore the selected index. For example, let sql ignore the primary key:

select id from abce ignore index(primary)  where ... ;

  

5. Modify the logical structure of the business, thereby modifying the SQL statement

 

6. Use of negative index

select id, type, age from abce 
where type = 12345 and age> 3 
order by id + 0; #In this way id + 0 is a function operation, the index on id is not used

 

7. Modify the structure of SQL, so that the optimizer thinks that the cost of selecting the index will be higher

select id, type, age from abce
where type=12345 and age > 3
order by id;
#修改成
select id, type, age from abce
where type=12345 and age > 3
order by id,type, age;

In this way, there may be an opportunity for the optimizer to think that the cost of choosing to use the index on id will be higher. Thereby choosing another index.

(The above id is only used as an example, not necessarily the column of the primary key)

 

8. Sometimes it may be a bug, report the bug and wait for the official fix.

 

Guess you like

Origin www.cnblogs.com/abclife/p/12728005.html