Database: combined index

The combined index multi-field is ordered and is a complete BTree index , with the leftmost principle .

The leftmost principle :
multi-column indexing is to sort the first column first, and then sort the second column based on the order of the first column, if there is no first column, directly access the second column, then the second The columns must be unordered, and the direct access to the following columns will not use the index.
The search needs to start from the root node, the upper node corresponds to the left value, and the search needs to start from the root node, otherwise it does not start from the root node, and the subsequent nodes correspond to the lower value, which is still out of order and needs to be traversed, so the index is invalid Yes, so there is the leftmost principle.

 

Examples of combined indexes:

CREATE TABLE mytable( 
	ID INT NOT NULL, 
	username VARCHAR(16) NOT NULL, 
	city VARCHAR(50) NOT NULL, 
	age INT NOT NULL 
);

It is to build name, city, age into an index:

ALTER TABLE mytable ADD INDEX name_city_age (name(10),city,age);

When creating the table, the length of usernname is 16, and 10 is used here. This is because under normal circumstances, the length of the name will not exceed 10, which will speed up the index query speed, but also reduce the size of the index file and improve the update speed of INSERT.

If you create a single-column index on usernname, city, and age, and let the table have three single-column indexes, the efficiency of the combined index when querying will be very different, which is much lower than our combined index. Although there are three indexes at this time, MySQL can only use one of them, which it seems to be the most efficient single-column index.

The establishment of such a combined index is actually equivalent to the establishment of the following three sets of combined indexes:
    usernname, city, age  
    usernname, city  
    usernname  

Why is there no combined index like city and age? This is because of the result of the MySQL combination index "leftmost prefix".

 

Published 162 original articles · won 30 · 90,000 views +

Guess you like

Origin blog.csdn.net/ScorpC/article/details/104389338