当前位置:网站首页>How MySQL uses indexes (glory Collection Edition)
How MySQL uses indexes (glory Collection Edition)
2022-07-28 02:25:00 【Dragon back ride Shi】

Catalog
3、 ... and 、 What conditions can be used to index
Four 、Between and Like To deal with
One 、 Preface
Hello everyone , I am procedural -- Handong , I'm here again !!
stay MySQL In the middle of SQL When optimizing , Often in some cases , Yes MySQL There's some confusion about using indexes .
for example :
- MySQL Stop matching when you encounter range query criteria , So what are the scope conditions ?
- MySQL stay LIKE How to make use of index in fuzzy matching ?
- MySQL In what circumstances can we use index to sort ?
today , I will use a model , Answer all these questions one by one , Make you right MySQL The use of indexes is no longer daunting
Two 、 Knowledge supplement
key_len
EXPLAIN There is a column in the implementation plan key_len Used to indicate in this query , How many bytes is the selected index length , Usually we can judge how many columns are selected in the union index .
ad locum key_len The rule of size is :
- In a general way ,key_len Equal to index column type byte length , for example int The type is 4 bytes,bigint by 8 bytes;
- If it is a string type , You also need to consider character set factors , for example :CHAR(30) UTF8 be key_len At least 90 bytes;
- If the column type definition allows NULL, Its key_len We need to add more 1 bytes;
- If the column type is variable length , for example VARCHAR(TEXT\BLOB The entire column is not allowed to be indexed , If you create a partial index, it's also considered a dynamic column type ), Its key_len We need to add more 2 bytes;
3、 ... and 、 What conditions can be used to index
By summarizing a lot MYSQL Blogger's blog , It gives me a good inspiration , Then combine your own understanding , Made this picture 
At first glance , Is it dizzy , Don't worry , Let's take a slow look at
There are three parts in the picture :
- Index Key :MySQL It's used to determine the data range of the scan , In fact, it can be used MySQL Index part , Embodied in Key Length.
- Index Filter:MySQL Used to determine which data can be filtered by index , In the activation of ICP after , You can use the index part .
- Table Filter:MySQL Can't filter with index , After fetching the row data back to the table , To server Layer for data filtering .
We unfold in detail .
Index Key
Index Key It's used to determine MySQL A scanning range of , It can be divided into upper boundary and lower boundary .
MySQL utilize =、>=、> To determine the lower boundary (first key), Use the leftmost principle , First, judge that the first index key value is in where Is there... In the condition , If there is , Then judge the comparison symbol , If (=,>=) One of the , Add the definition of the lower boundary , Then continue to judge the next index key , If there is and is (>), Then add the key value to the lower boundary , Stop matching next index key ; If it doesn't exist , Directly stop the lower boundary matching .
exp:
idx_c1_c2_c3(c1,c2,c3)
where c1>=1 and c2>2 and c3=1
--> first key (c1,c2)
--> c1 by '>=' , Add the lower boundary , Continue to match the next
-->c2 by '>', Add the lower boundary , Stop matching Upper boundary (last key) And the lower boundary (first key) similar , First, judge whether it is (=,<=) One of the , If it is , Add definition , Continue to the next key match , If it is (<), Add definition , Stop matching
exp:
idx_c1_c2_c3(c1,c2,c3)
where c1<=1 and c2=2 and c3<3
--> last key (c1,c2,c3)
--> c1 by '<=', Add the upper boundary , Continue to match the next
--> c2 by '=' Add the upper boundary , Continue to match the next
--> c3 by '<', Add the upper boundary , Stop matching notes : The simple memory here is , If the comparison symbol contains '=' Number ,'>=' It also contains '=', Then the index key can be used , You can continue to match the following index key values ; If it doesn't exist '=', That is to say '>','<', these two items. , Later index key values can't match . meanwhile , The upper and lower boundaries cannot be mixed , Which boundary can take advantage of the key value of the index , It is the number of index keys that can be used finally .
Index Filter
Literally, we can use index to filter . That is, the field is in the index key value , But it can't be used to determine Index Key Part of .
exp:
idex_c1_c2_c3
where c1>=1 and c2<=2 and c3 =1
index key --> c1
index filter--> c2 c3Why... Here index key It's just c1 Well ? because c2 It's used to determine the upper boundary , But on the upper boundary c1 There was no (<=,=), And in the lower boundary ,c1 yes >=,c2 There was no , therefore index key Only c1 Field .c2,c3 All appear in the index , Be treated as index filter.
Table Filter
Can't use index to complete filtering , You can only use table filter. At this point, the engine layer will return the row data to server layer , then server Layer for table filter.
Four 、Between and Like To deal with
So if there is between and like,MySQL How to deal with it ?
Between
where c1 between 'a' and 'b' Equivalent to where c1>='a' and c1 <='b', So replace it accordingly , And then take the upper model , Just determine the upper and lower boundaries
Like
The first thing to confirm is % It can't be on the far left ,where c1 like '%a' Such a query can't take advantage of the index , Because index matching needs to conform to the leftmost prefix principle
where c1 like 'a%' In fact, it's equivalent to where c1>='a' and c1<'b' You can think about it .
5、 ... and 、 Sort index
In the database , If you can't use the index to complete the sorting , As the amount of data filtered goes up , The cost of sorting will be more and more , Even with limit, But the database will choose to sort all the result sets , Take the ordered limit Record , and MySQL For those that can be sorted by index limit There is optimization , More cost reduction .
Make sure it uses index It is very important to have ORDER BY with LIMIT executed without scanning and sorting full result set, so it is important for it to use index – in this case index range scan will be started and query execution stopped as soon as soon as required amount of rows generated.
CREATE TABLE `t1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`c1` int(11) NOT NULL DEFAULT '0',
`c2` int(11) NOT NULL DEFAULT '0',
`c3` int(11) NOT NULL DEFAULT '0',
`c4` int(11) NOT NULL DEFAULT '0',
`c5` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_c1_c2_c3` (`c1`,`c2`,`c3`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4
select * from t1;
+----+----+----+----+----+----+
| id | c1 | c2 | c3 | c4 | c5 |
+----+----+----+----+----+----+
| 1 | 3 | 3 | 2 | 0 | 0 |
| 2 | 2 | 4 | 5 | 0 | 0 |
| 3 | 3 | 2 | 4 | 0 | 0 |
| 4 | 1 | 3 | 2 | 0 | 0 |
| 5 | 1 | 3 | 3 | 0 | 0 |
| 6 | 2 | 3 | 5 | 0 | 0 |
| 7 | 3 | 2 | 6 | 0 | 0 |
+----+----+----+----+----+----+
7 rows in set (0.00 sec)
select c1,c2,c3 from t1;
+----+----+----+
| c1 | c2 | c3 |
+----+----+----+
| 1 | 3 | 2 |
| 1 | 3 | 3 |
| 2 | 3 | 5 |
| 2 | 4 | 5 |
| 3 | 2 | 4 |
| 3 | 2 | 6 |
| 3 | 3 | 2 |
+----+----+----+
7 rows in set (0.00 sec) There is a table ,c1,c2,c3 There's an index on it ,select c1,c2,c3 from t1; The query goes through index full scan , So the data presented is equivalent to... Without an index select c1,c2,c3 from t1 order by c1,c2,c3; Result
therefore , What is the order rule of index ?
c1=3 —> c2 Orderly ,c3 disorder
c1=3,c2=2 — > c3 Orderly
c1 in(1,2) —> c2 disorder ,c3 disorder
There's a little rule ,idx_c1_c2_c3, So how to make sure that a certain field is ordered ?c1 At the top of the index , It must be orderly ,c2 In the second position , Only in c1 The only time to determine a value ,c2 It's order , If c1 There are multiple values , that c2 Will not necessarily be orderly , Empathy ,c3 It's similar
6、 ... and 、 Summary
in the light of MySQL Indexes , I just mentioned the model in the case of single table query , Through this article , I think you should know MySQL How indexes are used in most cases , If in doubt , Please feel free to contact me. ?
You can see it here , Just click on it. Well .
边栏推荐
- 四种常见的 POST 提交数据方式
- Sample imbalance - entry 0
- QGIS mapping: vector data mapping process and export
- 软考 --- 数据库(2)关系模型
- Codeworks round 807 (Div. 2) a-c problem solution
- 智能合约安全——selfdestruct攻击
- Flume(5个demo轻松入门)
- Structure pseudo class selector - find single - find multiple - nth of type and pseudo elements
- Promise from introduction to mastery (Chapter 4 async and await)
- 【Star项目】小帽飞机大战(五)
猜你喜欢

Promise从入门到精通 (第2章 Promise的理解和使用)

正则表达式

Promise from introduction to mastery (Chapter 2 understanding and use of promise)

MYSQL解决死锁之路 - 常见 SQL 语句的加锁分析

支付宝小程序授权/获取用户信息

软考 --- 数据库(2)关系模型

Record a production deadlock
![[advanced ROS] Lecture 9 robot model motion based on rviz and arbotix control](/img/7f/f0360210e8a9f7e45410d79635bfd9.png)
[advanced ROS] Lecture 9 robot model motion based on rviz and arbotix control
![[database data recovery] data recovery case of insufficient disk space of SQL Server database](/img/0e/908db40e1e8b7dd62e12558c1c6dc4.png)
[database data recovery] data recovery case of insufficient disk space of SQL Server database

小程序毕设作品之微信校园浴室预约小程序毕业设计成品(1)开发概要
随机推荐
Codeworks round 807 (Div. 2) a-c problem solution
Ceresdao: the world's first decentralized digital asset management protocol based on Dao enabled Web3.0
MySQL高可用和主从同步
Vxe table/grid cell grouping and merging
Likeshop takeout ordering system [100% open source, no encryption]
【愚公系列】2022年07月 Tabby集成终端的使用
Ceresdao: new endorsement of ventures Dao
智能合约安全——selfdestruct攻击
Promise从入门到精通(第3章 自定义(手写)Promise)
上课笔记(5)(1)——#593. 二分查找(binary)
小程序毕设作品之微信校园浴室预约小程序毕业设计成品(2)小程序功能
Skywalking distributed system application performance monitoring tool - medium
go 学习01
Eredi reappeared at the digital China Summit and continued to deepen the protection of green waters and mountains with science and technology
产品解读丨MeterSphere UI测试模块的设计与分布式扩展
LeetCode 热题 HOT 100 -> 3. 无重复字符的最长子串
了解加密行业的“下一个大趋势”——Ventures DAO
这个操作可能不值钱,但却值得学习 | 【图片批量裁剪】
Leetcode hot topic Hot 100 - > 2. Add two numbers
MPLS tunnel experiment