当前位置:网站首页>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

 Insert picture description here

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
    1. Non leaf nodes contain
      1. The data that the index points to
      2. The downward pointer
      3. Pointer to data
  • 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 .

 Insert picture description here

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 .

 Insert picture description here

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\G

  • Use 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 by Compare with order by More damaging to performance , because group by Contained in the order by Sort 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 ):

  1. 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 )
  2. 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
原网站

版权声明
本文为[I'm afraid I'm not retarded]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221440356257.html