当前位置:网站首页>MySQL performance optimization index

MySQL performance optimization index

2022-07-04 12:09:00 Peng_ zhj

MYSQL performance

As we develop projects that use more and more users , The database may store a lot of information , however , Once the amount of data increases sharply
Hou , Our efficiency can be extremely low , Then we may have to improve the current efficiency . There are many ways to improve efficiency , Index can help us improve the efficiency of database query

Test database efficiency

1) View the cumulative operation of the database

-- Query cumulative operation data impact 
show global status like 'Innodb_rows%';

 Insert picture description here

2) Analyze the execution efficiency of query statements

Insert tens of millions of records

create database db666;

use db666;

-- 1.  Preparation form 
CREATE TABLE `user`(
	id INT,
	username VARCHAR(32),
	`password` VARCHAR(32),
	sex VARCHAR(6),
	email VARCHAR(50)
);

-- 2.  Create stored procedure , Implement batch insert record 
DELIMITER $$ --  Declare that the end symbol of the stored procedure is $$
CREATE PROCEDURE auto_insert()
BEGIN
    DECLARE i INT DEFAULT 1;
	START TRANSACTION; --  Open transaction 
    WHILE(i<=10000000)DO
        INSERT INTO `user` VALUES(i,CONCAT('jack',i),MD5(i),'male',CONCAT('jack',i,'@itcast.cn'));
        SET i=i+1;
    END WHILE;
	COMMIT; --  Submit 
END$$ --  End of statement 
DELIMITER ; --  Redeclare the semicolon as the closing symbol 

-- 3.  View stored procedures 
SHOW CREATE PROCEDURE auto_insert;

-- 4.  Calling stored procedure 
CALL auto_insert();

Test the length of a query statement :

select * from user where username='jack1000000';  //  Time consuming :6-8 second 

problem : In the case of tens of millions of data , A simple query takes too long , If complex queries take longer to execute , Think about users

3) Record query time-consuming statements

The database comes with logging : Slow query log

-- Check the startup of slow query log 
show variables like '%slow_query_log%';
-- View the slow query event configuration 
show variables like'%long_query_time%';

 Insert picture description here
Open slow query log

set global slow_query_log = on;

Set slow query sql Time threshold for

--  Global configuration ( Effective next time ...)
set global long_query_time=3;
--  temporary ( conversation ) To configure ( This session window takes effect )
set session long_query_time=3;

Test slow query logging

 Inquire about :select * from user where id=22;

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-t9YacKpG-1644671350719)(assets\02.bmp)]
Slow query log file analysis
 Insert picture description here

MYSQL Indexes

1. Indexes

  • The process of sorting data is called Indexing
  • Let's check according to the index , Improve query efficiency , Reduce time-consuming

2.MySQL Index classification

  • Primary key ( constraint ) Indexes
    A primary key is an index , Having constraints on the basis of indexes ( Non empty and unique ) Behavior
    Primary key constraint + Improve query efficiency

  • only ( constraint ) Indexes
    Unique constraint + Improve query efficiency

  • General index
    Only improve query efficiency

  • Combine ( union ) Indexes
    Multiple fields form an index to improve query efficiency

3. MySQL Index Syntax

3.1 Create index

① Create directly 【 understand 】

  • The primary key index cannot be created directly with
--  Create a normal index 
create index  Index name  on  Table name ( Field );

--  Create unique index 
create unique index  Index name  on  Table name ( Field );


--  Create a common federated index 
create index  Index name  on  Table name ( Field 1, Field 2);

--  Create a unique federated index 
create unique index  Index name  on  Table name ( Field 1, Field 2);

Code display

--  Create student table 
CREATE TABLE student(
 id INT,
 name VARCHAR(32),
 email VARCHAR(40)
);

-- name Field to set the general index 
CREATE INDEX name_idx ON student(name);

-- email Field sets a unique index 
CREATE UNIQUE INDEX telephone_uni_idx ON student(email);

② Specify when modifying a table 【 understand 】

--  Add a primary key , This means that the index value must be unique , And cannot be NULL
alter table  Table name  add primary key( Field );   --- The default index name of the primary key :primary key

--  Add unique index ( except NULL Outside ,NULL Can appear many times )
alter table  Table name  add unique( Field );      ---  Default index name : Field name 

--  Add a normal index 
alter table  Table name  add index( Field );      --- Default index name : Field name 

Code display

--  Appoint id Index for primary key 
ALTER TABLE student ADD PRIMARY KEY(id);
--  Appoint name For general index 
ALTER TABLE student ADD INDEX(name);
--  Appoint email For unique index 
ALTER TABLE student ADD UNIQUE(email);

③ Specify... When creating a table 【 master 】

--  Create a teacher list 
CREATE TABLE teacher(
 id INT PRIMARY KEY AUTO_INCREMENT, --  primary key 
 `name` VARCHAR(32),
 email VARCHAR(40) UNIQUE, --  unique index 
 sex VARCHAR(5),
 birthday DATE,
 INDEX(`name`) --  General index 
);

3.2 Delete index

--  Delete directly 
drop index  Index name  on  Table name ;

--  Delete when modifying table 
alter table  Table name  drop index  Index name ;

4. Advantages and disadvantages of index

*  advantage 
		 Improve query efficiency 
*  shortcoming 
		 Index takes up disk space 
		 Add records 、 to update 、 When modifying , The index is also updated , It will indirectly affect the efficiency of the database .

5. Index creation principles

1.  Regular use where Fields for conditional search 

2.  Fields that often use table joins ( Internal connection 、 External connection )  Foreign keys 

3.  Frequently sorted fields  order by

*  Be careful : The index itself takes up disk space , Not all fields are suitable for adding indexes ....

6. Common index failures

-- 1. Use like Fuzzy matching ,% When wildcards are used on the leftmost side 
select * from user where email like '%jack1234567%';
-- 2. Avoid using or, If there is a condition that has no index , Then a full table scan will be performed 
select * from user where id = 88 or password = xxxx;
-- 3. Calculate on index column 
select * from user where  id+1 = 88;
-- 4. Data type mismatch 
select * from user where  username = "123";  correct 
select * from user where  username = 123;  Index failure 
原网站

版权声明
本文为[Peng_ zhj]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141328146519.html