当前位置:网站首页>Several ways of MySQL database optimization (pen interview must ask)
Several ways of MySQL database optimization (pen interview must ask)
2022-07-06 09:35:00 【Jiang Xia】
Author platform :
| CSDN:blog.csdn.net/qq_4115394…
| Nuggets :juejin.cn/user/651387…
| You know :www.zhihu.com/people/1024…
| GitHub:github.com/JiangXia-10…
| official account :1024 note
This article altogether 3929 word , Estimated reading time 10 minute
Preface
I've changed jobs recently , I have been interviewing some time ago, and some questions are asked more frequently , Here is some sorting and summary , I hope I can help students who are also preparing to find jobs .
Among them, questions about databases are asked frequently , Then the frequency of asking about database, especially about database optimization, is basically that every company will ask . So here is a summary of the content about database optimization , Some of them are their own experience in peacetime development , Some of them are self-study contents . So if there is anything wrong, please discuss and correct it !
Text
In fact, the optimization of database will not only try to ask more on the pen , It's really because in actual work , Database optimization can affect the performance of the system , It's really important , Therefore, it is often necessary to write reasonable sql Script , And optimize the database . The optimization of database can be mainly considered from the following aspects :
1、 Select the most appropriate field properties
MySQL It can support large amount of data access , But generally speaking , The smaller the table in the database , The faster queries are executed on it . therefore , When creating tables , For better performance , We can set the size of the fields in the table as reasonable as possible , It is not necessary to choose the largest .
for example , stay user If username Set this field to varchar(255), Obviously, it will add unnecessary space to the database , Because we know that names can't reach such a long length anyway . alike .
Another way to improve efficiency is to , You should try to set the field to NOTNULL, In this way, when the query is executed in the future , Databases don't have to be compared NULL value .
For some text fields , Such as “ Gender ”, We can define them as ENUM type . Because in MySQL in ,ENUM Type is treated as numeric data , Numerical data can be processed much faster than text types . such , We can improve the performance of the database .
2、 Rational design table
about mysql It is best to follow the following principles in the design of the table :
a、 Data volume of single table
All tables need to be annotated , It is suggested that the data quantity of single table should be controlled within 3000 All within ;
Try not to save large field data , For example, do not store pictures in the database 、 Big data such as files ;
b、 Table usage specification
You need to split large fields and fields with low access frequency , Separate hot and cold data ;
When you create a data table , Try to limit the number of fields in a single table to 20 Within fields ;
c、 The index specification
Creating an index can greatly improve the efficiency of data access , But the index should be created reasonably , such as :
1、 The number of indexes in a single table should not exceed 5 individual , And the number of fields in a single index does not exceed 5 individual ;
2、INNODB Auto increment columns are recommended for primary keys , The primary key should not be modified , Strings should not be primary keys , If you don't specify a primary key ,INNODB Instead of using a unique and non null index ;
3、 If it's a composite index , Distinguish the largest field before the index ;
4、 Avoid redundant or duplicate indexes : Reasonably create a federated index ( Avoid redundancy );
5、 Don't index low base sequences , for example ‘ Gender ’ Such fields ;
6、 Mathematical and functional operations are not performed on index columns
Some incorrect index usage will lead to index invalidation , Refer to previous articles : A few things you must master SQL Optimization techniques ( 7、 ... and ): The best way to use an index
3、 Use connections (JOIN) Instead of subquery (Sub-Queries)
We often need to pass some sub queries , Use the result of the query as a condition in another query .MySQL from 4.1 Start supporting SQL Subquery of . for example , We need to find out the basic information of the students who fail the exam , You need to check the score of the failed students from the score table first id, Then query the basic information data from the students' basic information table :
select cname,age,gender from student where id in (select stu_id from score where score<60)
Although subqueries can be used to complete many tasks at one time, which logically require multiple steps SQL operation , At the same time, transaction or table lock can be avoided , And it's easy to write . however , The sentence written like this is very verbose , Query efficiency is also relatively slow , Therefore, under certain circumstances , Subqueries can be used more efficiently join replace . For example, the above query statement can be written like this
select cname,age,gender from student s left join score c on s.id=c.stu_id where c.score<60
Use join Why it's more efficient , Because MySQL You don't need to create a temporary table in memory to complete this logical two-step query .
4、 Business
We know that in many cases , For some database operations, you can only use one or a few SQL Statement can be completed . More often than not, you need to use a series of statements to complete a certain task . But in this case , When one of the statements in this block runs wrong , The operation of the whole statement block will become uncertain . A classic example , Bank transfer requires an account deduction , Deposit into an account , If one a The account has been deducted successfully , At this time, something unexpected happened suddenly , Or there is an error in the execution of the following statement ,b The account has not been deposited , At this time, the consistency of data is destroyed , Nor does it conform to atomicity . So you need to use transactions at this time . You can refer to the previous article about transactions : The isolation level of the transaction .
Things with BEGIN Keyword start ,COMMIT Keyword end . In the middle of this SQL operation failed , that ,ROLLBACK Command to restore the database to BEGIN The state before the beginning . such as
BEGIN;
INSERT INTO student SET cname=' Jiangxia ';
UPDATE score set score=99 where id=20
COMMIT;
Another important role of transactions is when multiple users use the same data source at the same time , It can use the method of locking database to provide users with a safe access way , This can ensure that the user's operation is not interfered by other users .
5、 Using the foreign key
Sometimes foreign keys can be used to ensure the relevance of data .
for example , Using foreign keys in the score table can ensure that each score record points to the corresponding student . ad locum , Foreign keys can put score In the table sty_id Mapping to student In the table id, This will ensure that no one is legal stu_id None of the records will be updated or inserted into score in .
The foreign key syntax is as follows :
The specific syntax format is as follows :
[CONSTRAINT < Foreign key name >] FOREIGN KEY Field name [, Field name 2,…]
REFERENCES < Main table name > Primary key column 1 [, Primary key column 2,…]
For two tables that have an association , The table where the primary key in the associated field is located is the primary table ( Parent table ), The table where the foreign key is located is the slave table ( Sub table ).
When defining a foreign key , The following rules need to be followed :
1、 The primary table must already exist in the database , Or the table that is currently being created . In the latter case , Then the master table and the slave table are the same table , Such a table is called a self reference table , This structure is called self referential integrity . The primary key must be defined for the primary table .
2、 Primary key cannot contain null value , But null values are allowed in foreign keys . in other words , As long as each non null value of the foreign key appears in the specified primary key , The content of this foreign key is correct .
3、 Specify the column name or combination of column names after the table name of the main table . This column or combination of columns must be the primary key or candidate key of the main table .
4、 The number of columns in the foreign key must be the same as the number of columns in the primary key of the primary table .
5、 The data type of the column in the foreign key must be the same as that of the corresponding column in the primary key of the primary table .
6、 Use index
Index is a common method to improve database performance , It allows the database server to retrieve specific rows much faster than without an index , Especially in the query statements include MAX(),MIN() and ORDERBY When these orders come , The performance improvement is more obvious .
Which fields should be indexed ?
As a general rule , Indexes should be built on those that will be used for JOIN,WHERE Judgement and ORDERBY Sort the fields on . Try not to index a field with a lot of duplicate values in the database . For one ENUM For fields of type , It is possible that a large number of repetitions will occur
for example user In the table “ Gender ” Indexing fields will not help , It's also possible to degrade the performance of the database . When creating tables, you can create appropriate indexes at the same time , You can also use ALTER TABLE or CREATE INDEX Create indexes later . Besides ,MySQL From version 3.23.23 Start supporting full text indexing and search . Full text index in MySQL There is a FULLTEXT Type index , But only for MyISAM Type of watch . For a large database , Loading data into a system without FULLTEXT In the indexed table , And then use ALTER TABLE or CREATE INDEX Create index , It will be very fast . But if you load data into an existing FULLTEXT In the indexed table , The execution will be very slow .
For some use of index, please refer to the previous article : A few things you must master SQL Optimization techniques ( 7、 ... and ): The best way to use an index ; Don't you know what a database index is .
7、 Lock the table
Because during the execution of a transaction , The database will be locked , Therefore, other user requests can only wait temporarily until the transaction ends . In some cases, we can get better performance by locking the magnification of the table .
A lock is a flag associated with a table .MySQL Allow client sessions to explicitly acquire table locks , To prevent other sessions from accessing the same table for a specific period of time . A client session can only acquire or release table locks for itself . It cannot acquire or release table locks for other sessions .
The following statement explicitly obtains the table lock :
LOCK TABLES table_name [READ | WRITE]
To lock a table , Can be in LOCK TABLES Keyword followed by its name . Besides , You can also specify the type of lock , It can be READ or WRITE.
To release the lock on the table , Please use the following sentence :
UNLOCK TABLES;
summary
That's about mysql Some points in database optimization , Database optimization is not only a knowledge point often asked in pen interviews , It is also often used in practical development and Application , If there is anything wrong, welcome to discuss and correct ! And if there are other better methods or places not mentioned in this article , Also welcome to exchange and discuss !
Related to recommend
边栏推荐
- Design and implementation of film and television creation forum based on b/s (attached: source code paper SQL file project deployment tutorial)
- Global and Chinese market of linear regulators 2022-2028: Research Report on technology, participants, trends, market size and share
- CSP salary calculation
- Le modèle sentinelle de redis
- Hard core! One configuration center for 8 classes!
- [Yu Yue education] reference materials of power electronics technology of Jiangxi University of science and technology
- IDS cache preheating, avalanche, penetration
- QML type: locale, date
- 【深度学习】语义分割:论文阅读(NeurIPS 2021)MaskFormer: per-pixel classification is not all you need
- Meituan Er Mian: why does redis have sentinels?
猜你喜欢

五月集训总结——来自阿光
![[deep learning] semantic segmentation: paper reading: (CVPR 2022) mpvit (cnn+transformer): multipath visual transformer for dense prediction](/img/f1/6f22f00843072fa4ad83dc0ef2fad8.png)
[deep learning] semantic segmentation: paper reading: (CVPR 2022) mpvit (cnn+transformer): multipath visual transformer for dense prediction

Full stack development of quartz distributed timed task scheduling cluster

Redis之哨兵模式

Sentinel mode of redis

Oom happened. Do you know the reason and how to solve it?

MapReduce instance (VII): single table join

基于B/S的影视创作论坛的设计与实现(附:源码 论文 sql文件 项目部署教程)

Redis之Geospatial

Advanced Computer Network Review(4)——Congestion Control of MPTCP
随机推荐
Multivariate cluster analysis
Parameterization of postman
Kratos ares microservice framework (I)
英雄联盟轮播图自动轮播
Kratos战神微服务框架(二)
Seven layer network architecture
Take you back to spark ecosystem!
leetcode-14. Longest common prefix JS longitudinal scanning method
Scoped in webrtc_ refptr
面渣逆袭:Redis连环五十二问,图文详解,这下面试稳了
Redis之cluster集群
Processes of libuv
MapReduce instance (V): secondary sorting
Global and Chinese market of linear regulators 2022-2028: Research Report on technology, participants, trends, market size and share
How to intercept the string correctly (for example, intercepting the stock in operation by applying the error information)
One article read, DDD landing database design practice
Reids之删除策略
LeetCode41——First Missing Positive——hashing in place & swap
AcWing 2456. Notepad
MapReduce instance (VIII): Map end join