search
HomeDatabaseMysql TutorialIn-depth understanding of indexes in MySQL (use, classification, matching methods)

This article will give you an in-depth understanding of the index in MySQL, and introduce the advantages, uses, classifications, technical terms and matching methods of the index. I hope it will be helpful to you!

In-depth understanding of indexes in MySQL (use, classification, matching methods)

For advanced development, we often have to write some complex SQL, so to prevent writing inefficient SQL, we need to understand some basic knowledge of indexing. Through these basic knowledge we can write more efficient SQL. [Related recommendations: mysql video tutorial]

01 The advantages of indexing

  • are greatly reduced The amount of data that the server needs to scan, that is, the amount of IO
  • Help the server avoid sorting and temporary tables (try to avoid file sorting, but use index sorting)
  • Turn random IO into sequential IO

02 The use of index

  • Quickly find rows matching the where clause
  • If possible When choosing among multiple indexes, MySQL will usually use the index with the fewest rows found. If the table has a multi-column index, the optimizer can use any left-most prefix of the index to find the row. When there is a table connection, retrieve row data from other tables
  • Find the min and max values ​​of a specific index column
  • If sorting or grouping can be done with the leftmost prefix of the index, then Tables are sorted and grouped
  • In some cases, queries can be optimized to retrieve data values ​​without having to find data rows
  • 03 Classification of indexes

The index created by the database by default is for a unique key

Primary key index (unique and not empty)

Unique index (the only one can be Empty)
  • Ordinary index (index of ordinary fields)
  • Full-text index (generally created with varchar, char, text types, but rarely used)
  • Combined index ( Index established by multiple words)
  • 04 Technical terms of index

1. Return to table

#The name field is an ordinary index. Find the primary key from the B-tree of the name column, and then find the final data from the B-tree of the primary key. This is the table return. (The leaf nodes of the primary key index save all the data of the column, but generally all leaf nodes save the corresponding primary key ID)

As shown in the figure: the index structure established by name in a use table sql is

select * from use where name='sun'

First, the primary key Id=2 corresponding to sun will be found through the non-primary key index name, and then the entire row data will be found in the primary key index through id=2, and Return, this is the return table.

In-depth understanding of indexes in MySQL (use, classification, matching methods)2. Covering index

You can query what you need on the non-primary key index Fields that do not need to be returned to the table to query again are called covering indexes.

As shown in the name index in the figure above, the sql is

select id,name from user where name = "1"

. The value of id is already available in the non-primary key index in the first step. There is no need to query row data in the primary key index based on ID.

3. Leftmost matching

In the combined index, the left side is matched first, and then the backward matching is continued; for example, in the user table The joint index composed of name and age, select * from user where name="Mr. Ji" and age = 18 is consistent with the leftmost matching and can be used as an index. However, select * from user where age = 18 does not comply and this index is not used.

Extension;

How to create an index if it is the following two sql
select * from user where name="纪先生" and age = 18;
select * from user where age = 18;

Due to the leftmost matching principle:

Only one needs to create a combined index age name Just

What if it is the following three sql

select * from user where name="纪先生" and age = 18;
select * from user where name= "纪先生";
Create name age and age indexes, or create age name and name indexes, both are fine.

In fact

name age and age are better

, because the index also needs to be stored persistently, occupying disk space, and also takes up memory when reading, name age and age name The occupancy is the same, but comparing name and age separately, age definitely takes up less space and name is longer (the larger the index, the more IO times)

Attention! Notice! Notice! :

When reading many articles, I often see some examples of leftmost matching errors:

If the index is a combined index of name age, sql is
select * from user where age = 18 and name="Mr. Ji"

Many people think that this cannot be indexed, but it is actually possible. The mysql optimizer will optimize the adjustment sequence and adjust it to name="Mr. Ji" and age = 18

##4. Index pushdown

Use index information as much as possible in the combined index to reduce the number of table returns as much as possible

案例:还是 name+age的组合索引如果没有索引下推的查询是 在组合索引中通过name查询所有匹配的数据,然后回表根据ID查询对于的数据行,之后在筛选出符合age条件的数据。索引下推就是组合索引中通过name查询匹配再根据age找到符合的数据ID,然后回表根据ID查询对应行数据,明显会减少数据的条数

05 索引匹配方式

mysql官网准备了一些学习测试的数据库,可以直接下载通过source导入到我们自己的数据库

官网地址:dev.mysql.com/doc/index-o…

In-depth understanding of indexes in MySQL (use, classification, matching methods)

如上图下载zip, 其中包含了sakila-schema.sql和sakila-data.sql,分别是sakila的库,表和数据的创建脚本。

mysql> source /Users/ajisun/Downloads/sakila-db/sakila-schema.sql;
mysql> source /Users/ajisun/Downloads/sakila-db/sakila-data.sql;

需要通过explain来查看索引的执行情况,执行计划以前有文章详细讲过,具体参考执行计划explain

1. 全值匹配

指和某个索引中的所有列进行匹配,例如使用数据库sakila中的staff

新建一个三个字段的联合索引:

mysql> alter table staff add index index_n1(first_name,last_name,username);

执行sql:

mysql> explain select * from staff where first_name='Mike' and last_name='Hillyer' and username='Mike'复制代码

In-depth understanding of indexes in MySQL (use, classification, matching methods)

其中的ref是三个const, 用到三个字段,能全匹配一条数据

2. 最左前缀匹配

只匹配组合索引中前面几个字段

执行sql:

mysql> explain select * from staff where first_name='Mike' and last_name='Hillyer';

In-depth understanding of indexes in MySQL (use, classification, matching methods)

ref只出现2个const,比上面全值匹配少一个,就只匹配了前面两个字段

3. 匹配列前缀

可以匹配某一列的的开头部分,像like属性

执行sql:

mysql> explain select * from staff where first_name like 'Mi%';

In-depth understanding of indexes in MySQL (use, classification, matching methods)

type=range ,是个范围查询,可以匹配一个字段的一部分,而不需要全值匹配

如果有模糊匹配的字段不要放在索引的最前面,否则有索引也不能使用,如下

In-depth understanding of indexes in MySQL (use, classification, matching methods)

4. 匹配一个范围值

可以查找某一个范围的数据

mysql> explain select * from staff where first_name > 'Mike';

In-depth understanding of indexes in MySQL (use, classification, matching methods)

5. 精确匹配某一列并范围匹配另一列

可以查询第一列的全部和另一列的部分

mysql> explain select * from staff where first_name = 'Mike' and last_name like 'Hill%';

In-depth understanding of indexes in MySQL (use, classification, matching methods)

6. 只访问索引的查询

查询的时候只需要访问索引,不需要访问数据行,其实就是索引覆盖

mysql> explain select first_name,last_name,username from staff where first_name='Mike' and last_name='Hillyer';

In-depth understanding of indexes in MySQL (use, classification, matching methods)

extra=Using index 说明是使用了索引覆盖,不需要再次回表查询。

其实一张表中有索引并不总是最好的。总的来说,只有当索引帮助存储引擎快速提高查找到记录带来的好处大于其带来的额外工作时,索引才是有效的。对应很小的表,大部分情况下没有索引,全表扫描更高效;对应中大型表,索引时非常有效的;但是对于超大的表,索引的建立和使用代价也就非常高,一般需要单独处理特大型的表,例如分区,分库,分表等。

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of In-depth understanding of indexes in MySQL (use, classification, matching methods). 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
图文详解mysql架构原理图文详解mysql架构原理May 17, 2022 pm 05:54 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于架构原理的相关内容,MySQL Server架构自顶向下大致可以分网络连接层、服务层、存储引擎层和系统文件层,下面一起来看一下,希望对大家有帮助。

mysql怎么替换换行符mysql怎么替换换行符Apr 18, 2022 pm 03:14 PM

在mysql中,可以利用char()和REPLACE()函数来替换换行符;REPLACE()函数可以用新字符串替换列中的换行符,而换行符可使用“char(13)”来表示,语法为“replace(字段名,char(13),'新字符串') ”。

mysql的msi与zip版本有什么区别mysql的msi与zip版本有什么区别May 16, 2022 pm 04:33 PM

mysql的msi与zip版本的区别:1、zip包含的安装程序是一种主动安装,而msi包含的是被installer所用的安装文件以提交请求的方式安装;2、zip是一种数据压缩和文档存储的文件格式,msi是微软格式的安装包。

mysql怎么去掉第一个字符mysql怎么去掉第一个字符May 19, 2022 am 10:21 AM

方法:1、利用right函数,语法为“update 表名 set 指定字段 = right(指定字段, length(指定字段)-1)...”;2、利用substring函数,语法为“select substring(指定字段,2)..”。

mysql怎么将varchar转换为int类型mysql怎么将varchar转换为int类型May 12, 2022 pm 04:51 PM

转换方法:1、利用cast函数,语法“select * from 表名 order by cast(字段名 as SIGNED)”;2、利用“select * from 表名 order by CONVERT(字段名,SIGNED)”语句。

MySQL复制技术之异步复制和半同步复制MySQL复制技术之异步复制和半同步复制Apr 25, 2022 pm 07:21 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于MySQL复制技术的相关问题,包括了异步复制、半同步复制等等内容,下面一起来看一下,希望对大家有帮助。

带你把MySQL索引吃透了带你把MySQL索引吃透了Apr 22, 2022 am 11:48 AM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了mysql高级篇的一些问题,包括了索引是什么、索引底层实现等等问题,下面一起来看一下,希望对大家有帮助。

mysql怎么判断是否是数字类型mysql怎么判断是否是数字类型May 16, 2022 am 10:09 AM

在mysql中,可以利用REGEXP运算符判断数据是否是数字类型,语法为“String REGEXP '[^0-9.]'”;该运算符是正则表达式的缩写,若数据字符中含有数字时,返回的结果是true,反之返回的结果是false。

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor