当前位置:网站首页>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;
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
边栏推荐
- VPS installation virtualmin panel
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23
- array_ The contains() function uses
- Dos and path
- Lecture 9
- Detailed explanation of classic process synchronization problems
- DDS-YYDS
- Btrace tells you how to debug online without restarting the JVM
- Configure SSH certificate login
- os. Path built-in module
猜你喜欢
Application of slice
os. Path built-in module
Using terminal connection in different modes of virtual machine
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 10
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 7
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 5
Introduction of network security research direction of Shanghai Jiaotong University
Ultimate bug finding method - two points
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 22
The frost peel off the purple dragon scale, and the xiariba people will talk about database SQL optimization and the principle of indexing (primary / secondary / clustered / non clustered)
随机推荐
[Chongqing Guangdong education] National Open University spring 2019 2727 tax basis reference questions
QQ get group information
Review of week 278 of leetcode II
SSH principle and public key authentication
Foreach (system.out:: println) usage
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 16
SAP ui5 date type sap ui. model. type. Analysis of the display format of date
Snowflake won the 2021 annual database
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 7
Realize cross tenant Vnet connection through azure virtual Wan
Supercomputing simulation research has determined a safe and effective carbon capture and storage route
Here, the DDS tutorial you want | first experience of fastdds - source code compilation & Installation & Testing
Configure SSH key to realize login free
Install freeradius3 in the latest version of openwrt
QQ get group member operation time
[ES6] template string: `string`, a new symbol in es2015
Ultimate bug finding method - two points
Polymorphic system summary
No response after heartbeat startup
Map container