当前位置:网站首页>MySQL advanced part 2: the use of indexes
MySQL advanced part 2: the use of indexes
2022-07-05 06:13:00 【Dawnlighttt】
List of articles
Use of index
Index is one of the most common and important means of database optimization , Indexing can usually help users solve most of MySQL Performance optimization problem of .
Verifying indexes improves query efficiency
In the table structure we prepared tb_item in , A total of 300 Ten thousand records ;
A. according to ID Inquire about
select * from tb_item where id = 1999\G;
Fast query , near 0s , The main reason is that id Primary key , There is an index ;
2). according to title Make a precise inquiry
select * from tb_item where title = 'iphoneX Move 3G 32G941'\G;
see SQL Statement execution plan :
Treatment scheme , in the light of title Field , Create index :
create index idx_item_title on tb_item(title);
After the index is created , Check again :
adopt explain , View execution plan , perform SQL The index just created is used
Use of index
Prepare the environment
create table `tb_seller` (
`sellerid` varchar (100),
`name` varchar (100),
`nickname` varchar (50),
`password` varchar (60),
`status` varchar (1),
`address` varchar (100),
`createtime` datetime,
primary key(`sellerid`)
)engine=innodb default charset=utf8mb4;
insert into `tb_seller` (`sellerid`, `name`, `nickname`, `password`, `status`, `address`, `createtime`) values('alibaba',' Alibaba ',' Ali shop ','e10adc3949ba59abbe56e057f20f883e','1',' The Beijing municipal ','2088-01-01 12:00:00');
insert into `tb_seller` (`sellerid`, `name`, `nickname`, `password`, `status`, `address`, `createtime`) values('baidu',' Baidu Technology Co., Ltd ',' Baidu store ','e10adc3949ba59abbe56e057f20f883e','1',' The Beijing municipal ','2088-01-01 12:00:00');
insert into `tb_seller` (`sellerid`, `name`, `nickname`, `password`, `status`, `address`, `createtime`) values('huawei',' Huawei Technology Co., Ltd ',' Huawei store ','e10adc3949ba59abbe56e057f20f883e','0',' The Beijing municipal ','2088-01-01 12:00:00');
insert into `tb_seller` (`sellerid`, `name`, `nickname`, `password`, `status`, `address`, `createtime`) values('itcast',' Chuanzhi podcast Education Technology Co., Ltd ',' Spreading wisdom Podcast ','e10adc3949ba59abbe56e057f20f883e','1',' The Beijing municipal ','2088-01-01 12:00:00');
insert into `tb_seller` (`sellerid`, `name`, `nickname`, `password`, `status`, `address`, `createtime`) values('itheima',' Black horse programmer ',' Black horse programmer ','e10adc3949ba59abbe56e057f20f883e','0',' The Beijing municipal ','2088-01-01 12:00:00');
insert into `tb_seller` (`sellerid`, `name`, `nickname`, `password`, `status`, `address`, `createtime`) values('luoji',' Logitech Technology Co., Ltd ',' Logitech shop ','e10adc3949ba59abbe56e057f20f883e','1',' The Beijing municipal ','2088-01-01 12:00:00');
insert into `tb_seller` (`sellerid`, `name`, `nickname`, `password`, `status`, `address`, `createtime`) values('oppo','OPPO Technology Co., Ltd ','OPPO Official flagship store ','e10adc3949ba59abbe56e057f20f883e','0',' The Beijing municipal ','2088-01-01 12:00:00');
insert into `tb_seller` (`sellerid`, `name`, `nickname`, `password`, `status`, `address`, `createtime`) values('ourpalm',' Zhangqu Technology Co., Ltd ',' Zhangqu shop ','e10adc3949ba59abbe56e057f20f883e','1',' The Beijing municipal ','2088-01-01 12:00:00');
insert into `tb_seller` (`sellerid`, `name`, `nickname`, `password`, `status`, `address`, `createtime`) values('qiandu',' QIANDU Technology ',' QianDu store ','e10adc3949ba59abbe56e057f20f883e','2',' The Beijing municipal ','2088-01-01 12:00:00');
insert into `tb_seller` (`sellerid`, `name`, `nickname`, `password`, `status`, `address`, `createtime`) values('sina',' Sina Technology Co., Ltd ',' Sina's official flagship store ','e10adc3949ba59abbe56e057f20f883e','1',' The Beijing municipal ','2088-01-01 12:00:00');
insert into `tb_seller` (`sellerid`, `name`, `nickname`, `password`, `status`, `address`, `createtime`) values('xiaomi',' Xiaomi Tech ',' Xiaomi's official flagship store ','e10adc3949ba59abbe56e057f20f883e','1',' Xi'an City ','2088-01-01 12:00:00');
insert into `tb_seller` (`sellerid`, `name`, `nickname`, `password`, `status`, `address`, `createtime`) values('yijia',' IKEA ',' IKEA flagship store ','e10adc3949ba59abbe56e057f20f883e','1',' The Beijing municipal ','2088-01-01 12:00:00');
-- Create a federated index
create index idx_seller_name_sta_addr on tb_seller(name,status,address);
Avoid index invalidation
1). Full match , Specify specific values for all columns in the index . In this case , The index works , High execution efficiency .
explain select * from tb_seller where name=' Xiaomi Tech ' and status='1' and address=' The Beijing municipal ';
2). The leftmost prefix rule
If you index multiple columns , Follow the leftmost prefix rule . It means that the query starts from the top left of the index , And don't skip columns in the index .
( Imagine climbing stairs )
Match the leftmost prefix rule , Go to the index :
Illegal leftmost prefix rule , Index failure :
If the law of the left is the best , But there was a jump in a column , Only the leftmost column index takes effect :
3). Range query right column , Index cannot be used . Fields after range query criteria , Index failure
According to the first two fields name , status Queries are indexed , But the last condition address No index is used .
4). Do not operate on index columns , Index will fail .
5). String without single quotes , Cause index invalidation .
because , The query is , No single quotes for Strings ,MySQL The query optimizer for , It will automatically perform type conversion , Cause index invalidation .
6). Try to use overlay index , avoid select *
Try to use overlay index ( Queries that only access the index ( Index column contains query column completely )), Reduce select * .
If the query column , Out of index columns , It also reduces performance .( Index column has no password, So you need to go back to the table to query )
TIP :
using index : When using overlay index, it will appear
using where: In the case of search using index , You need to go back to the table to query the required data
using index condition: Search uses index , But you need to return the table to query the data
using index ; using where: Search uses index , But all the data needed can be found in the index column , So you don't need to go back to the table to query the data
7). use or The conditions of separation , If or The columns in the previous condition are indexed , And there's no index in the next column , Then the indexes involved will not be used .
Example ,name Fields are index columns , and createtime It's not an index column , In the middle is or Connection is not indexed :
explain select * from tb_seller where name=' Black horse programmer ' or createtime = '2088-01-01 12:00:00'\G;
8). With % At the beginning Like Fuzzy query , Index failure .
If it's just tail blur matching , The index will not fail . If it's a fuzzy head match , Index failure .
Solution : Solve by overriding the index
9). If MySQL Evaluation uses indexes more slowly than full tables , Index is not used .
Mingming created... Alone address Indexes , however explain View unused indexes , This situation is related to the data in the table , Look at the table data to know ,12 Data ,11 The bar is ’ The Beijing municipal ’, Using index lookup is not as efficient as direct full table scanning , So in the implementation SQL At the time of statement ,MySQL Discard index , And using a full table scan .
10). is NULL , is NOT NULL Sometimes
Index failure .
MySQL The bottom layer will automatically judge , If the full table scan is fast , Then directly use the full table to scan , Don't walk index . If most of the index column data in the table is non null , Then use is not null Go when you need to , Use is null Don't leave the index when ( It's not as fast as full table scanning ), Full table scan ; vice versa .
11). in Go to the index , not in Index failure .
12). Single column index and composite index .
Try to use composite indexes , Use less single column indexes .
Create composite index
create index idx_name_sta_address on tb_seller(name, status, address);
It's like creating three indexes :
name
name + status
name + status + address
Create a single column index
create index idx_seller_name on tb_seller(name);
create index idx_seller_status on tb_seller(status);
create index idx_seller_address on tb_seller(address);
When using a single column index , The database will choose an optimal index ( The most recognizable index ) To use , Not all indexes will be used .
Check index usage
show status like 'Handler_read%'; -- View current session index usage
show global status like 'Handler_read%'; -- View global index usage
Handler_read_first: The number of times the first item in the index has been read . If it's higher , Indicates that the server is performing a large number of full index scans ( The lower the value, the better ).
Handler_read_key: If the index is working , This value represents the number of times a row has been read by the index value , If the value is lower , Indicates that the performance improvement of index is not high , Because indexes are not often used ( The higher the value, the better ).
Handler_read_next : Number of requests to read next line in key order . If you use range constraints or if you perform index scans to query index columns , The value increases .
Handler_read_prev: Number of requests to read the previous line in key order . This reading method is mainly used to optimize ORDER BY ... DESC.
Handler_read_rnd : The number of requests to read a line according to a fixed location . If you are executing a large number of queries and need to sort the results, the value is high . You may be using a lot of needs MySQL Scan the entire table for queries or your connection is not properly keyed . This is a higher value , It means that the operation efficiency is low , An index should be established to remedy .
Handler_read_rnd_next: Number of requests to read the next line in the data file . If you're doing a lot of scanning , The value is higher . Usually it means that your table index is not correct or the query written does not use the index .
边栏推荐
- Collection: programming related websites and books
- MIT-6874-Deep Learning in the Life Sciences Week 7
- 884. Uncommon words in two sentences
- 快速使用Amazon MemoryDB并构建你专属的Redis内存数据库
- 可变电阻器概述——结构、工作和不同应用
- [rust notes] 17 concurrent (Part 2)
- Appium automation test foundation - Summary of appium test environment construction
- Introduction to LVS [unfinished (semi-finished products)]
- Daily question 1984 Minimum difference in student scores
- New title of module a of "PanYun Cup" secondary vocational network security skills competition
猜你喜欢
How to adjust bugs in general projects ----- take you through the whole process by hand
[practical skills] technical management of managers with non-technical background
Dynamic planning solution ideas and summary (30000 words)
The connection and solution between the shortest Hamilton path and the traveling salesman problem
1.14 - 流水线
6. Logistic model
wordpress切换页面,域名变回了IP地址
Wazuh开源主机安全解决方案的简介与使用体验
Sqlmap tutorial (II) practical skills I
leetcode-6108:解密消息
随机推荐
Règlement sur la sécurité des réseaux dans les écoles professionnelles secondaires du concours de compétences des écoles professionnelles de la province de Guizhou en 2022
实时时钟 (RTC)
LVS简介【暂未完成(半成品)】
中职网络安全技能竞赛——广西区赛中间件渗透测试教程文章
leetcode-1200:最小绝对差
Daily question 1189 Maximum number of "balloons"
7. Processing the input of multidimensional features
MIT-6874-Deep Learning in the Life Sciences Week 7
“磐云杯”中职网络安全技能大赛A模块新题
leetcode-556:下一个更大元素 III
1041 Be Unique
快速使用Amazon MemoryDB并构建你专属的Redis内存数据库
R language [import and export of dataset]
可变电阻器概述——结构、工作和不同应用
1040 Longest Symmetric String
2022年贵州省职业院校技能大赛中职组网络安全赛项规程
SQLMAP使用教程(二)实战技巧一
【Rust 笔记】17-并发(上)
One question per day 2047 Number of valid words in the sentence
【Rust 笔记】15-字符串与文本(下)