当前位置:网站首页>2. MySQL index creation method and its optimization
2. MySQL index creation method and its optimization
2022-06-21 10:32:00 【I'm afraid I'm not retarded】
Index optimization analysis
Performance degradation ,SQL slow 、 Long execution time 、 Long waiting time
- Excessive data —— Sub database and sub table
- Too many tables associated , Too much join——SQL Optimize
- Not making full use of the index —— Index building
- Server tuning and parameter settings —— adjustment my.cnf
Optimization means “ Index ” The quickest and most commonly used .
preheating — Common and general join Inquire about

among :union Keywords when used , The fields of the two results are equal 、 Equal number of fields 、 The fields are in the same order .
union all and union The difference is that duplicate removal ,union It's going to be weightless .
select a.*,b.* from t_emp a
left join t_dept b on a.deptid = b.id
where b.id is null
union
select a.*,b.* from t_dept b
left join t_emp a on a.deptid = b.id
where a.id is null;
-- Inquire about a Table unique and b Table unique data
mysql Single table bottleneck 500w
Index introduction
Indexes (Index) Help MySQL Data structure for efficient data acquisition .
The essence of index : An index is a data structure
An index can be understood as " Quickly find data structures in order ".
The database system maintains a data structure that satisfies a specific search algorithm , These data structures reference data in some way , In this way, advanced search algorithms can be implemented on these data structures . These data structures are indexes .
Where the index is stored : Generally speaking , The index itself is big , It's impossible to store everything in memory , therefore , Indexes are often stored on disk in the form of index files .
Advantages of index :
- Improve the efficiency of data retrieval , Reduce the IO cost ;
- Sort data by index , Reduce the cost of sorting data , Reduce CPU Consumption of .
The disadvantages of indexing :
- While improving the query speed , Reduces the speed of table updates . Because when updating the table ,MySQL Not only save table data , You also need to save the index column fields added each time in the index file
- The index is actually a table , The table holds the primary key and index fields , And points to the record of the entity table , So the index also takes up space .
The structure of the index :
B_tree Balance tree
- Btree
- Non leaf nodes contain
- The data that the index points to
- The downward pointer
- Pointer to data
- Non leaf nodes contain
- B+tree
- Non leaf nodes do not contain the data pointed to by the index
MySQL choice B+tree As index , Relatively limited memory ,B+tree It takes up more space than Btree One third smaller , Relative occurrence IO Fewer times , Less time .
Time complexity
The same problem can be solved by different algorithms , The quality of an algorithm will affect the efficiency of the algorithm and program . The purpose of algorithm analysis is to select the appropriate algorithm and improve the algorithm .
O(n) Time complexity The algorithm varies by orders of magnitude n The increasing complexity in the time dimension .

Clustered index and non clustered index
Cluster index is not a separate index type , It's a way of storing data .
“ Clustering ” Indicates that data rows and adjacent inter value clusters are stored together .
Only the primary key index is a clustered index , That is, the index arranged in order .
In addition to the primary key index , Other indexes are non clustered indexes , characteristic : Non clustered indexes need to find all indexes .

mysql Index classification
Single value index
That is, an index contains only a single column , A table can have multiple single-column indexes
- Create an index with the table
create table
customer(
id int(10) unsigned auto_increment,
customer_no varchar(200),
customer_name varchar(200),
primary key(id),
key(customer_name)
);
-- key(customer_name) With the creation of the table , Create indexes at the same time
- Create a single valued index separately
CREATE INDEX idx_customer_name ON customer(customer_name) - Delete index
DROP INDEX idx_customer_name ON customer;
unique index
The value of the index column must be unique , But you can have an empty value CREATE UNIQUE INDEX [indexName] ON table_name(column)
primary key
After setting it as the primary key, the database will automatically create an index ,Innodb Index for clustering
Composite index
That is, an index contains multiple columns . Create an index for multiple fields
create index idx_age_deptid_name on t_emp(age,deptid,name)
The result of the query by matching the index is n Data , That is, if a composite index contains several fields, it will return the query results of several fields .
Basic grammar
establish
create [unique] index [indexName] on table_name(column)Create a single value index
Give table t_emp In the table name Field creation index :
create index idx_name on t_emp(name)The creation of a unique index
stay mysql in , With the creation of the primary key, the index will be automatically generated , Therefore, the unique index can be set for the unique fields in the data set of other fields in the table
Create a unique index for the employee number field in the employee table
create unique index idx_empno in temp(emp_no)Composite index
Delete
drop index [indexName] on mytable;see
show index from table_name\GUse alter command ( General use create That's enough )
-- There are four ways to add indexes to data tables alter table tbl_name add primary key(column_list); -- This statement adds a primary key , This means that the index value must be unique and not empty alter table tbl_name add unique index_name(column_list); -- The value of the index created by this statement must be unique ( except Null Outside ,Null There may be many times alter table tbl_name add index index_name(column_list); -- Add a normal index , Index values can appear multiple times alter table tbl_name add fulltext index_name(column_list); -- This statement specifies that the index is fulltext, For full-text indexing
When to create an index
- The primary key automatically creates a unique index ;;
- Fields that are frequently used as query criteria should be indexed ;
- Fields associated with other tables in the query , Index foreign key relationship ;
- Single key / The choice of Composite Index , Composite index is more cost-effective ;
- Fields sorted in the query , If the sorting field is accessed through the index, the sorting speed will be greatly improved ;
- Statistics or grouping fields in a query ,
group byCompare withorder byMore damaging to performance , becausegroup byContained in theorder bySort first, then group .
In those cases, it is not allowed to create an index
- There are too few records
- A table or field that is frequently added, deleted, or queried
- where There is no need to create an index for fields that are not used in the condition
- Those with poor filtering are not suitable for index creation
Measure whether the index should be built , How to build an index “ Ruler ”
Explain Namely mysql Provided to users “ Ruler ”
One 、Explain What is it? ( View execution plan )
Implementation plan : stay MySQL In the logical architecture optimizer( Optimizer ) Adjust without changing the query results sql Execution order , Generate execution plan .
Use EXPLAIN Keyword can simulate optimizer execution SQL Query statement , So they know MySQL How to deal with you SQL Of the statement . Analyze the performance bottleneck of your query statement or table structure .
Two 、Explain Can do ?
Read order of tables
Which indexes can be used
Operation type of data read operation
Which indexes are actually used
References between tables
How many rows per table are physically queried
3、 ... and 、Explain How to use it?
EXPLAIN sql Query statement
Explain sql sentence Return to right sql Statement analysis .
Information contained in the implementation plan ( pivotal ):
id
- select The serial number of the query , Contains a set of numbers , Represents execution in a query select The order of clauses or operation tables
- Three id situation :
- id Same number : The order of execution is from top to bottom ( Analysis table shown )
- id inequality : If it's a subquery ,id The serial number of will increase ,id The higher the priority, the higher , The first to be executed ;
- id In the column id There are both similarities and differences : According to the first id Different , Press again id Prioritize the same
- concerns :id Number, each number , Represents an independent query , One sql The fewer query times, the better .( The same number represents a query )
type
Shows what type of query is used .
From the best to the worst :
system>const>eq_ref>ref>range>index>ALL
- all: Full table scan 、 Extremely inefficient ( When type This keyword appears in the field , It can be indexed )
- index: Overlay index , appear index when sql Index is used but not filtered by index , Generally, the overlay index is used or the index is used for sorting and grouping ;( It needs to be optimized )
- range: Retrieve only rows in the given range , Use an index to select rows .key Column shows which index is used . It's usually in your where In the sentence between、<、>、in And so on , This range scan index scan is better than full table scan , Because it just needs to start at a certain point in the index , And end at another point , It does not involve scanning all indexes
边栏推荐
- 中国国际电子商务中心与易观分析联合发布:2021年4季度全国网络零售发展指数同比增长0.6%
- Uni app advanced creation component / native rendering [Day9]
- Application configuration management, basic principle analysis
- 金融机构抢滩“数字员工”;保险APP适老化服务评测框架发布
- Bit segment operation of STM32, LED lighting based on stm32f103xxx multiple methods
- 远程办公市场调查报告
- The bilingual live broadcast of Oriental selection is popular, and the transformation of New Oriental is beginning to take shape
- Definition of annotations and annotation compiler
- 燎原之势 阿里云数据库“百城聚力”助中小企业数智化转型
- Equals and hashcode
猜你喜欢

DSP online upgrade (2) -- design framework of bootloader

New programmers optimize a line of code on Monday and are discouraged on Wednesday?

The bilingual live broadcast of Oriental selection is popular, and the transformation of New Oriental is beginning to take shape

Lodash real on demand approach

Where is the cow in Shannon's information theory?

Les nouveaux programmeurs optimisent une ligne de code lundi et sont exhortés à se retirer mercredi?

聊聊大火的多模态项目

About Alipay - my savings plan - interest rate calculation instructions

Starting a prairie fire, Alibaba cloud database "hundred cities gather together" to help small and medium-sized enterprises' digital intelligence transformation

The first phase of takin open source training camp is coming! Teach you to complete the full link voltage test hand in hand!
随机推荐
从零开始做网站10-后台管理系统开发
香农的信息论究竟牛在哪里?
Introduction and template of segment tree Foundation (I)
Odd number of characters exception
113. summary of common usage of moment.js
Audio and video format introduction, encoding and decoding, audio and video synchronization
Inner class
DSP gossip: how to save the compiled variables on the chip when the variables are defined in the code
A bit of knowledge - what is amp?
Esp8266/esp32 +1.3 "or 0.96" IIC OLED pointer clock
Haplotype analysis using shapeit
使用shapeit进行单倍型分析
聊聊大火的多模态项目
TC软件概要设计文档(手机群控)
程序員新人周一優化一行代碼,周三被勸退?
Tensorflow, danger! Google itself is the one who abandoned it
Matplotlib two methods of drawing torus!
111. solve the problem of prohibiting scripts from running on vs code. For more information, see error reporting
How to be an interesting person
Optimisation des performances - compression, chargement et formatage des images