search
HomeDatabaseMysql TutorialWhat is the leftmost prefix principle of Mysql index?

Preface

The reason why there is this leftmost prefix index

In the final analysis, it is the database structure B tree of mysql

In practical problems, for example

The index index (a, b, c) has three fields,

Use the query statement select * from table where c = '1', the sql statement will not go to the index Index

select * from table where b =‘1’ and c ='2' This statement will not go through index index

1. Definition

Leftmost prefix matching principle: When MySQL builds a joint index, it will abide by the leftmost prefix matching principle, that is, leftmost priority. When retrieving data, match from the leftmost of the joint index.

For better To identify this situation, analyze it by creating tables and indexes

2. Full index order

Create a table and create a joint index. If the order is reversed, it can still be identified. , but there must be all parts of it

Create table

CREATE TABLE staffs(
	id INT PRIMARY KEY AUTO_INCREMENT,
	`name` VARCHAR(24) NOT NULL DEFAULT'' COMMENT'姓名',
	`age` INT NOT NULL DEFAULT 0 COMMENT'年龄',
	`pos` VARCHAR(20) NOT NULL DEFAULT'' COMMENT'职位',
	`add_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT'入职时间'
)CHARSET utf8 COMMENT'员工记录表';

INSERT INTO staffs(`name`,`age`,`pos`,`add_time`) VALUES('z3',22,'manager',NOW());
INSERT INTO staffs(`name`,`age`,`pos`,`add_time`) VALUES('July',23,'dev',NOW());
INSERT INTO staffs(`name`,`age`,`pos`,`add_time`) VALUES('2000',23,'dev',NOW());

Create indexALTER TABLE staffs ADD INDEX index_staffs_nameAgePos(name,age,pos);

The order of the indexname-age-pos

Show whether the index has oneshow index from staffs;

What is the leftmost prefix principle of Mysql index?

##By reversing the order of its left and right, its execution is the same

The main statements are these three sentences

  1. explain select *from staffs where name='z3'and age=22 and pos='manager';

  2. ##explain select *from staffs where pos='manager' and name='z3 'and age=22;

  3. explain select *from staffs where age=22 and pos='manager' and name='z3';

What is the leftmost prefix principle of Mysql index?The order of the above three is reversed, and the joint index is used.

The main reason is that there is a query optimizer explain in MySQL. Therefore, the order of the fields in the sql statement does not need to be the same as the order of the fields defined by the joint index. The query optimizer will judge and correct the order in which the SQL statement is executed efficiently, and finally generate a real execution plan

The joint index can be used in any order

3. Partial index order

3.1 Positive order

If it is in order (missing arms and legs), all It’s the same

  1. explain select *from staffs where name=‘z3’;

  2. ##explain select *from staffs where name='z3’and age=22;
  3. ##explain select *from staffs where name='z3’and age=22;
The types are all ref types, but the field length will change slightly, that is, the word length it defines changes

What is the leftmost prefix principle of Mysql index?3.2 Out of order

If the order of some indexes is out of order

Only check the first index

explain select *from staffs where name= 'z3';
  1. Skip the middle index

    explain select *from staffs where name='z3' and pos='manager';
  2. Only check the last index

    explain select *from staffs where pos='manager';
  3. ##You can find the positive sequence

If you are missing arms or legs, you will still use the normal indexWhat is the leftmost prefix principle of Mysql index?

Even if you skip the middle index, you can still use the index to query

But if you only check the last index

type is the all type, and the entire table is directly queried (this is because there is no matching from the beginning of name, and if it directly matches pos, it will appear out of order,)

Sometimes type is the index type, because it can still be queried through the index

index scans all index trees, while all scans the entire disk data in the entire table

4. Fuzzy index

A similar fuzzy index will use the like statement

So the following three statements

if compounded with the leftmost prefix, will Use range or index type for indexing

##explain select *from staffs where name like '3%';

Leftmost prefix index, type is index or range

  1. explain select *from staffs where name like '%3%'; Type is all, full table query

  2. explain select *from staffs where name like '%3%';, type is all, full table query

  3. # #5. Range index

  4. If when querying multiple fields, there is a range in the middle, it is recommended to delete the index and eliminate the middle index

The specific ideas are as followsWhat is the leftmost prefix principle of Mysql index?

建立一张单表

CREATE TABLE IF NOT EXISTS article(
	id INT(10) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
	author_id INT(10) UNSIGNED NOT NULL,
	category_id INT(10) UNSIGNED NOT NULL,
	views INT(10) UNSIGNED NOT NULL,
	comments INT(10) UNSIGNED NOT NULL,
	title VARCHAR(255) NOT NULL,
	content TEXT NOT NULL
);

INSERT INTO article(author_id,category_id,views,comments,title,content)
VALUES
(1,1,1,1,'1','1'),
(2,2,2,2,'2','2'),
(1,1,3,3,'3','3');

经过如下查询:

explain SELECT id, author_id FROM article WHERE category_id = 1 AND comments > 1 ORDER BY views DESC LIMIT 1;

What is the leftmost prefix principle of Mysql index?

发现其上面的单表查询,不是索引的话,他是进行了全表查询,而且在extra还出现了Using filesort等问题

所以思路可以有建立其复合索引

具体建立复合索引有两种方式:

  1. create index idx_article_ccv on article(category_id,comments,views);

  2. ALTER TABLE 'article' ADD INDEX idx_article_ccv ( 'category_id , 'comments', 'views' );

What is the leftmost prefix principle of Mysql index?

但这只是去除了它的范围,如果要去除Using filesort问题的话,还要将其中间的条件范围改为等于号才可满足

发现其思路不行,所以删除其索引 DROP INDEX idx_article_ccv ON article;

What is the leftmost prefix principle of Mysql index?

主要的原因是:

这是因为按照BTree索引的工作原理,先排序category_id,如果遇到相同的category_id则再排序comments,如果遇到相同的comments 则再排序views。

当comments字段在联合索引里处于中间位置时,因comments > 1条件是一个范围值(所谓range),MySQL无法利用索引再对后面的views部分进行检索,即range类型查询字段后面的索引无效。

所以建立复合索引是对的

但是其思路要避开中间那个范围的索引进去

只加入另外两个索引即可create index idx_article_cv on article(category_id, views);

What is the leftmost prefix principle of Mysql index?

The above is the detailed content of What is the leftmost prefix principle of Mysql index?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Apr 16, 2025 am 12:20 AM

ACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.

MySQL: Database Management System vs. Programming LanguageMySQL: Database Management System vs. Programming LanguageApr 16, 2025 am 12:19 AM

MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

MySQL: Managing Data with SQL CommandsMySQL: Managing Data with SQL CommandsApr 16, 2025 am 12:19 AM

MySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.

MySQL's Purpose: Storing and Managing Data EffectivelyMySQL's Purpose: Storing and Managing Data EffectivelyApr 16, 2025 am 12:16 AM

MySQL is an efficient relational database management system suitable for storing and managing data. Its advantages include high-performance queries, flexible transaction processing and rich data types. In practical applications, MySQL is often used in e-commerce platforms, social networks and content management systems, but attention should be paid to performance optimization, data security and scalability.

SQL and MySQL: Understanding the RelationshipSQL and MySQL: Understanding the RelationshipApr 16, 2025 am 12:14 AM

The relationship between SQL and MySQL is the relationship between standard languages ​​and specific implementations. 1.SQL is a standard language used to manage and operate relational databases, allowing data addition, deletion, modification and query. 2.MySQL is a specific database management system that uses SQL as its operating language and provides efficient data storage and management.

Explain the role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor