当前位置:网站首页>Mysql database optimization details
Mysql database optimization details
2022-06-11 14:58:00 【Ant】
MySql Database optimization details
MySQL The optimization of database performance is MySQL The only way for the development of database , MySQL Database performance optimization is also MySQL Witness to the progress of the database . Record some MySQL Some details of optimization
Select the most appropriate field properties ( Source )
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 width of the fields in the table as small as possible . for example , When defining the zip code field , If you set it to CHAR(255), Obviously added unnecessary space to the database , Even use VARCHAR This type is also redundant , because CHAR(6) You can finish the task very well . alike , If you can , We should use MEDIUMINT instead of BIGIN To define integer fields .
Another way to improve efficiency is to , You should try to set the field to NOT NULL, In this way, when the query is executed in the future , Databases don't have to be compared NULL value .
For some text fields , for example “ Province ” perhaps “ 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 .
Use connections (JOIN) Instead of subquery (Sub-Queries)( Source )
MySQL from 4.1 Start supporting SQL Subquery of . This technology can be used SELECT Statement to create a single column query result , Then use this result as a filter in another query . for example , We want to delete the customer without any order in the customer basic information table , You can use the subquery to select all the customers who place orders from the sales information table ID out , Then pass the results to the main query , As shown below :
DELETE FROM customerinfo WHERE CustomerID NOT in (SELECT CustomerID FROM salesinfo );
Using subquery can complete many logical steps at once SQL operation , At the same time, transaction or table lock can be avoided , And it's easy to write . however , In some cases , Subqueries can be connected more efficiently (JOIN).. replace . for example , Suppose we want to take out all the users who have no order records , You can use the following query to complete :
SELECT * FROM customerinfoWHERE CustomerID NOT in (SELECT CustomerID FROM salesinfo )
If connection is used (JOIN).. To complete this query , It's going to be a lot faster . Especially when salesinfo The table is right CustomerID If there is an index , Performance will be better , Enquiries are as follows :
SELECT * FROM customerinfoLEFT JOIN salesinfo ON customerinfo.CustomerID=salesinfo.CustomerID WHERE salesinfo.CustomerID IS NULL
Connect (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 .
Use Union (UNION) Instead of manually created temporary tables ( Source )
MySQL from 4.0 Version of starts to support UNION Inquire about , It can take two or more items that need to use temporary tables SELECT Query merge in a query . At the end of the client's query session , Temporary tables are automatically deleted , So as to ensure that the database is neat 、 Efficient . Use UNION To create a query , We just need to use UNION As a keyword, put multiple SELECT Just connect the statements , It's important to note that all SELECT The number of fields in a statement should be the same as . The following example demonstrates the use of UNION Query for .
SELECT Name, Phone FROM client UNION SELECT Name, BirthDate FROM author UNION SELECT Name, Supplier FROM product
Business ( Source )
Although we can use subqueries (Sub-Queries)、 Connect (JOIN) And union (UNION) To create a variety of queries , But not all database operations 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 . imagine , To insert a data into two associated tables at the same time , This may happen : After the first table is successfully updated , There's an unexpected situation in the database , The operation in the second table is not completed , such , It will result in incomplete data , It even destroys the data in the database . To avoid this situation , You should use transactions , Its function is : Or each statement in the statement block is operated successfully , Or they all failed . let me put it another way , It can keep the consistency and integrity of data in the database . 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 .
BEGIN; INSERT INTO salesinfo SET CustomerID=14; UPDATE inventory SET Quantity=11 WHERE item='book'; 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 .
Don't do the following
- Explicit or implicit type conversions such as
SELECT id FROM table WHERE id='1'Another example is inWHEREclausenumericThe type andintColumn comparison of type belongs to implicit conversion - Use different types of columns for equivalent queries
- stay WHERE In Clause
"="The left expression performs the function 、 Arithmetic operations or other expression operations - Use the prefix
%OfLIKE - Use negative query , Such as
NOT,!=,<>,!>,1<,NOT EXISTS,NOT INas well asNOT LIKEsuch asNOT INWill empty andNULLFind out - Run large queries in the database
- Single
SQLStatement to update multiple tables at the same time - Using cross library queries
It is recommended to split into a single table for simple query , Association by program
Avoid the following operations
- Avoid big business Keep things simple , The length of the whole transaction should not be too long . It's complicated to split
SQLFor the multiple smallSQL, Avoid big business - Avoid using : trigger 、 function 、 stored procedure 、 View
- Avoid mathematical operations in the database
MySQLNot good at mathematical operation and logical judgment - Avoid taking out large fields and useless content
SELECTGet only the necessary fields , Use... As little as possibleSELECT * - Avoid using large tables
JOIN - Avoid updating too much data at once such as , Update the data in batches after breaking up
- Try to avoid using subqueries , It is recommended to convert subqueries into associative queries But because subqueries do not use indexes , In the case of associative queries that do not use indexes , Subqueries are better than associative queries . Therefore, as for whether to use association query or sub query, you need to use
EXPLAINYesSQLAnalysis is the best policy
Replace with
- use
INInstead ofORORThe efficiency is notINThe high efficiency INThe number of data in the condition is suggested to be controlled within 500 Within a Learn to useEXISTSInstead ofIN,EXISTSIn some scenarios, the query will be better thanINfast- use
UNION ALLInstead ofUNION - Use
EXISTSTo determine whether records exist , Instead of usingSELECT COUNT(1)To determine whether records exist
Sharing plans
Blog content will be synchronized to Tencent cloud + Community , Invite everyone to join us :https://cloud.tencent.com/
license agreement
In this paper A signature - Noncommercial use - Share in the same way 4.0 The international license agreement , Reprint please indicate the source .
边栏推荐
- In the "ten billion blue ocean" database, each player can find a boat | c-position face-to-face
- Dynamically set the layoutinflater of the layout
- Hamad application layout scheme 05 of hashicopy (visit the web page)
- MySQL user authority summary [user authorization required]
- 数字化转型项目做了多年,主架构师都绝望了:当初就不应该用外包!
- 以 Log4j 为例,如何评估和划分安全风险
- 大道至簡 | 設計 ViT 到底怎麼配置Self-Attention才是最合理的?
- 深度剖析「圈组」关系系统设计 | 「圈组」技术系列文章
- Flutter 3.0 was officially released: it stably supports 6 platforms, and byte jitter is the main user
- How to play seek tiger, which has attracted much attention in the market?
猜你喜欢

大道至简 | 设计 ViT 到底怎么配置Self-Attention才是最合理的?

Did you break the rules?

Social software soul withdraws its IPO application: Tencent is a major shareholder

【SystemVerilog 之 接口】~ Interface

Elk log analysis system

B站高管解读财报:疫情对公司长期发展无影响 视频化趋势不可阻挡

Tencent interviewers share their interview experience, how to evaluate the interviewers' technical and personal comprehensive quality, and give you some suggestions on the interview

Sum of two leetcode numbers

How to manually package your own projects

【SystemVerilog 之 验证】~ 测试平台、硬件设计描述、激励发生器、监测器、比较器
随机推荐
When open source meets KPI, globalization vs localization, how can the ideal and reality of open source be reconciled?
In depth research and analysis report on global and Chinese high purity molybdenum market
化“被动”为“主动”,如何构建安全合规的智能产品 | Q推荐
In depth research and analysis report on global and Chinese gas monitor market
漫画:有趣的 “切蛋糕“ 问题
A former employee of Baidu was awarded 1.07 million yuan for job hopping; Apple, Google and Microsoft plan to "kill" the password; It is said that Geely has acquired Meizu | Q information
gensim.models word2vec 参数
Nexus of repository manager
Nexus configuration Yum repository for repository manager
Backtracking / activity scheduling maximum compatible activities
数据库“百亿蓝海”中,每位玩家都能找到一叶扁舟 | C位面对面
01discussion on Tekton
汤峥嵘:CTO 是商业思维和技术思维交汇的那个点
02 Tekton Pipeline
Seven parameters of thread pool and reject policy
Managing technology debt in a microservice architecture
High number_ Chapter 6 infinite series__ Marklaurin series
A brief talk on the feelings after working at home | community essay solicitation
In depth research and analysis report on global and Chinese smart lamp Market
Oauth2的理解