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

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%';

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)]](/img/50/ce9e64fd17ccc1514a14537dd05f1f.jpg)
Slow query log file analysis 
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 efficiencyonly ( constraint ) Indexes
Unique constraint + Improve query efficiencyGeneral index
Only improve query efficiencyCombine ( 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
边栏推荐
- Summary of collection: (to be updated)
- QQ set group information
- LVS load balancing cluster deployment - Dr direct routing mode
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 24
- os. Path built-in module
- [solve the error of this pointing in the applet] SetData of undefined
- Common built-in modules
- Dos and path
- Process communication and thread explanation
- Method of setting default items in C # ComboBox control code
猜你喜欢

Attributes and methods in math library

Single spa, Qiankun, Friday access practice

Awk getting started to proficient series - awk quick start

(August 9, 2021) example exercise of air quality index calculation (I)

Clion configuration of opencv

Ultimate bug finding method - two points
![[solve the error of this pointing in the applet] SetData of undefined](/img/19/c34008fbbe1175baac2ab69eb26e05.jpg)
[solve the error of this pointing in the applet] SetData of undefined

Games101 Lesson 8 shading 2 Notes

Serialization oriented - pickle library, JSON Library

DDS-YYDS
随机推荐
template<typename MAP, typename LIST, typename First, typename ... Keytypes > recursive call with indefinite parameters - beauty of Pan China
os. Path built-in module
Climb Phoenix Mountain on December 19, 2021
Attributes and methods in math library
Clockwise rotation method of event arrangement -- PHP implementation
[Android reverse] function interception instance (③ refresh CPU cache | ④ process interception function | ⑤ return specific results)
Lecture 9
Understanding of object
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 18
2021 annual summary - it seems that I have done everything except studying hard
03_ Armv8 instruction set introduction load and store instructions
Anti clockwise rotation method of event arrangement -- PHP implementation
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 21
Exness: positive I win, negative you lose
Decrypt the advantages of low code and unlock efficient application development
Source code analysis of the implementation mechanism of multisets in guava class library
Alibaba cloud server connection intranet operation
Simple understanding of string
About the use of URL, href, SRC attributes
Login operation (for user name and password)