[Index] Talking about MySQL index

1. What is an index

The index is like the table of contents of a book, so, just like the books we read have tables of contents, the tables we build must also have indexes. The difference is that a book has only one directory, while a table can have multiple indexes (but only one primary key index).

The following table creation statement, in table T, idis the primary key index, index (k)which means setting k as a common index.

create table T(
id int primary key, 
k int not null, 
name varchar(16),
index (k));

2. Index structure

In InnoDB, the default engine of MySQL, the index structure is B+ tree (B+ tree only has leaf nodes to store data), and each index corresponds to a B+ tree, just like the above table, and each corresponds to a B+ 主键索引idtree 普通索引k. The difference is that id的B+树each leaf node stores the data of the row corresponding to the id, while k的B+树each leaf node stores the primary key (id) value corresponding to the k .

3. Return form

When we execute this statement, it will return to the table:

select * from T where k=10;

The execution process is as follows: first search the B+ tree of k, and the found data is the id value corresponding to k=10, and then search according to this id, and 主键索引id对应的B+树find the row corresponding to the id value. The process of returning to the primary key index search is called returning to the table .

Returning to the table will reduce the execution efficiency of SQL statements. How to avoid returning to the table? Then you need to use the primary key index:

select * from T where id=10;

Using the primary key index only needs to search the B+ tree once to get the result.

4. Covering index

Execute the following statement, which belongs to the covering index:

select id from T where k=10;

The execution process is as follows: first search the B+ tree of k, the leaf node of the tree stores the corresponding id value, and there is no need to return to the table at this time. That is to say, the results in the index k cover the results we want to query, which is the covering index.

5. The leftmost prefix principle

A joint index is an index composed of multiple columns. The construction of the joint index is based on the principle of the leftmost prefix. For example, if we construct a joint index of (a, b, c), then the leaf nodes on the B+ tree are ordered according to a , when a is equal, b is ordered, and when both a and b are equal, c is arranged according to the principle of order.
(1) When we execute a a=1,b=2,c=3query statement, both a and b can use the index;
(2) When we only execute b=2the query statement, the index is not used, because b is out of order;
( 3) And the fields after the range query do not use the index. For example, a=1 and b>2 and c=3when we query, a and b can use the index, but c cannot use the index.

Guess you like

Origin blog.csdn.net/m0_52373742/article/details/122797845
Recommended