Understanding of the leftmost principle of mysql joint index

Brother, I suddenly used a compound index, also called a joint index, to query data. But little is known about its principle.

Checked some information from the Internet, but also understand. Write it down now!

If there is a 2-column index (col1, col2), the index has been established on (col1), (col1, col2);
if there is a 3-column index (col1, col2, col3), then (col1) has been established , (col1,col2), (col1,col2,col3) indexes are established;

E.g:

Combined index (a,b)

explain select * from test where a=1 and b=1;
explain select * from test where b=1 and a=1;

In the query explanation, it is shown that the index is used because:

When mysql is processing the where condition, it optimizes the query conditions for a batch of matching index positions, and stops matching until a range query (>, <, between, like) is encountered, that is to say, mysql will automatically optimize the query conditions to match the index to meet the Conditions for using indexes.

In the above example, creating an (a,b) index is equivalent to creating an index a and an index ab (which can only be created in combination from left to right). In this way, the most frequently used fields are written in the front in the where condition, and they can also be matched.

but. There are also some examples, if there is only where b=1 in the where condition, will the composite index be used?

The answer is it will be used. The principle is:

According to the principle of mysql, as long as it is an index or a part of the index, it can be scanned in index mode (type type under explain), and mysql may use this composite index, but there is a fatal disadvantage! low efficiency. MySQL will search from the first data in the index to the last data one by one until it finds an index that meets the judgment conditions.

 

Note: Under what circumstances can a composite index be actually called? This composite index is used only when the leftmost index field is equalized first, and the subsequent fields become ordered. simply say. That is, the fields of the composite index are best ordered to ensure that it is used.

Indexing principles

1. The fewer the indexes, the better.
Reason: When modifying data, the first index must be updated to reduce the writing speed.
2. The narrowest field is placed on the left side of the key (this narrowest should mean the frequency of use)
3. Avoid file sort sorting, temporary tables and table scans.

References:

https://www.cnblogs.com/forcheryl/p/7389798.html

https://www.zhihu.com/question/36996520

https://www.cnblogs.com/jamesbd/p/4333901.html

 

Guess you like

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