Can the LIKE query in MySQL use the index

single column index

Using like x% query can use the index, but using like %x% and like %x query can not use the index

So why can't the index be used for like %x% and like %x queries?
Because the index is an ordered B+ Tree data structure, the leaf nodes are arranged in order from left to right. If you use like %x% and like %x to query, if you don’t know which one is the beginning, you will go to the full Table scan, so it is easy to understand

composite index

Use the fields username and age as a joint index and name it index_username_age.

use like x%

insert image description here
From the EXPLAIN execution plan, we can see that the query using like x% uses the index_username_age joint index. The type is range, which means that this is a range scan of the index (because it is fuzzy matching, and fuzzy matching can form a scan interval), and Extra is Using where;Using index, indicating that the index is used, but filtering is still required

Use like %x%

insert image description here

Use like %x

insert image description here
Judging from the execution plans using like %x% and like %x, their type is index, indicating that it has traversed the index B+ Tee, and Extra is Using where; Using index, indicating that the index is used, but it needs to be filtered

So why does it need to traverse the entire index B+ Tee when using like %x% and like %x queries? Because for the joint index index_username_age, it uses the username field to create and maintain the index B+ Tee. Naturally, the username field in the leaf nodes is arranged in an orderly manner, while the age field is unordered, only when the username field is the same , the age field is ordered; so if you use like %x% and like %x queries, you don’t know which one to start with, and you will scan the entire table.

in conclusion

Using like x%
In the joint index, using like x% query can use the index, whether it is using a covering index or querying all fields, it can use the index to improve query efficiency.
Use like %x% and like %x
to use the covering index: although the index is used, it needs to traverse the entire index B+ Tee, and then filter out the data that meets the conditions to
query all fields: at this time, it needs to read and traverse the joint index index_username_age The whole index B+ Tee, and then filter out the data that meets the conditions. Since the value of the address field is not saved in the joint index, it is necessary to go back to the table and find the corresponding record in the primary key index

Guess you like

Origin blog.csdn.net/yzx3105/article/details/130428478