Talk about the principle of the leftmost prefix of the composite index?

Analysis & Answer

An index in MySQL can refer to multiple columns in a certain order. This type of index is called a compound (joint) index.

If indexes A, B, (C, D) exist in table Ta

Rule 1: Match all columns

SELECT * FROM Ta  WHERE E = 'F1' AND A ='10001';
复制代码

If the index order is not followed, the mysql query optimizer will automatically adjust the order to use the defined index. If we reverse the order of the conditions in where, the effect is the same.

Rule 2: leftmost prefix match

SELECT * FROM Ta  WHERE  A ='10001' AND B = 'B001' ;
复制代码

When the query condition exactly matches one or several consecutive columns on the left of the index, only the prefix of the first column of the index is used .

Rule 3: The query condition does not specify the first column of the index

SELECT * FROM Ta  WHERE  D = 'D001' ;
复制代码

Since it is not the leftmost prefix, queries such as indexes obviously do not use indexes.

Rule 4: Match the prefix string of a column.

SELECT * FROM Ta  WHERE  C LINK 'C001%' ;
复制代码

The index can be used at this time, if the wildcard % does not appear at the beginning, the index can be used.

Rule 5: Range query (the columns behind the range query will not be able to use the index)

For range condition query, MYSQL can no longer use other index columns behind the range. However, there is no such restriction for multiple equivalent condition queries.

Rule 6: Query conditions contain functions or expressions

If the query conditions contain functions or expressions, MySQL will not use indexes for this column (although some can be used in a mathematical sense).

Reflect & Expand

How to create a reasonable index, how to optimize the index?

Meow Interview Assistant: One-stop solution to interview questions, you can search the WeChat applet [Meow Interview Assistant]  or follow [Meow Brush Questions] -> Interview Assistant  free questions. If you have good interview knowledge or skills, look forward to your sharing!

Guess you like

Origin blog.csdn.net/jjclove/article/details/127391403