当前位置:网站首页>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
边栏推荐
- [the way of programmer training] - 2 Perfect number calculation
- How do std:: function and function pointer assign values to each other
- Leetcode: 408 sliding window median
- 8.8.1-PointersOnC-20220214
- How to judge the advantages and disadvantages of low code products in the market?
- First knowledge of spark - 7000 words +15 diagrams, and learn the basic knowledge of spark
- Clion configuration of opencv
- Btrace tells you how to debug online without restarting the JVM
- AI should take code agriculture? Deepmind offers a programming version of "Alpha dog" alphacode that surpasses nearly half of programmers!
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 12
猜你喜欢

SAP ui5 date type sap ui. model. type. Analysis of the display format of date

netstat
![Entitas learning [3] multi context system](/img/f9/a3ce86ff2121dd1043305b7e834cc5.jpg)
Entitas learning [3] multi context system
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 24](/img/2e/b1f348ee6abaef24b439944acf36d8.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 24

OSI seven layer reference model

How to judge the advantages and disadvantages of low code products in the market?

Here, the DDS tutorial you want | first experience of fastdds - source code compilation & Installation & Testing

Leetcode: 408 sliding window median

Foreach (system.out:: println) usage
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23](/img/72/a80ee7ee7b967b0afa6018070d03c9.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23
随机推荐
Definition and method of string
About the use of URL, href, SRC attributes
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 5
Function parameters (positional parameters, default value parameters, variable parameters, named keyword parameters, keyword parameters)
Login operation (for user name and password)
Global function Encyclopedia
QQ get group link, QR code
Enter the smart Park, and change begins here
Possible to restore a backup of SQL Server 2014 on SQL Server 2012?
DVC use case (VI): Data Registry
Day01 preliminary packet capture
[ES6] template string: `string`, a new symbol in es2015
Video analysis
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 17
OSI seven layer model & unit
Daemon xinted and logging syslogd
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 16
Climb Phoenix Mountain on December 19, 2021
No response after heartbeat startup
(August 10, 2021) web crawler learning - Chinese University ranking directed crawler