当前位置:网站首页>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 .
边栏推荐
- Why can redis be so fast?
- Database optimization
- In depth research and analysis report on global and Chinese spray drying machinery market
- Hashicopy之nomad应用编排方案01
- one hundred and twenty-three thousand four hundred and sixty-five
- 数据库优化
- 百度某离职员工跳槽字节被判赔107万元;苹果谷歌微软拟“干掉”密码;传吉利已收购魅族|Q资讯
- In the "ten billion blue ocean" database, each player can find a boat | c-position face-to-face
- Cartoon: interesting "cake cutting" problem
- 化“被动”为“主动”,如何构建安全合规的智能产品 | Q推荐
猜你喜欢

思科瑞递交科创板注册:拟募资6亿 年营收2.22亿

对于事务的认识

Elk log analysis system

Did you break the rules?

Avenue to simplicity | how to configure self attention for vit is the most reasonable?

HMS core shows the latest open capabilities in mwc2022, helping developers build high-quality applications

With a loss of 13.6 billion yuan in three years, can listing revive Weima?

数据库优化

清北力压耶鲁,MIT蝉联第一,2023QS世界大学排名最新发布
![[SystemVerilog interface] ~ interface](/img/dc/0a9750cace1460af772e2f3f6a8763.png)
[SystemVerilog interface] ~ interface
随机推荐
Flutter 3.0 was officially released: it stably supports 6 platforms, and byte jitter is the main user
数据库“百亿蓝海”中,每位玩家都能找到一叶扁舟 | C位面对面
Leetcode daily question - plus one
Hamad application layout scheme 02 of hashicopy
In depth analysis of "circle group" relationship system design | series of articles on "circle group" technology
如何做好自媒体?这几个步骤你做对了吗?
化“被动”为“主动”,如何构建安全合规的智能产品 | Q推荐
Anaconda delete virtual environment
Live800: several ways for intelligent customer service to improve customer experience
Backtracking / solution space tree permutation tree
回溯法/解空间树 排列树
架构概念探索:以开发纸牌游戏为例
02 Tekton Pipeline
C # - how to add and read appsetting in the console application JSON file
Knowledge of affairs
Task manager based on Qt development
以 Log4j 为例,如何评估和划分安全风险
【SystemVerilog 之 接口】~ Interface
Qualcomm WLAN framework learning (29) -- 6GHz overview
gensim. Models word2vec parameter