search
HomeDatabaseMysql TutorialMySQL数据库优化中要用到哪些语句?

MySQL数据库优化中要用到哪些语句?

Jun 07, 2016 pm 04:09 PM
mysqlmainoptimizationWhichdatabasearticlestatement

以下的文章主要介绍的是MySQL数据库优化的实际操作以及相关推荐,前面我们也讲过一些相关的优化操作策略,我们今天就一起来看看MySQL数据库优化中Group BY 语句、 Order By语句 等。 优化GROUP BY语句 默认情况下,MySQL对所有GROUP BY col1,col2...的字段

以下的文章主要介绍的是MySQL数据库优化的实际操作以及相关推荐,前面我们也讲过一些相关的优化操作策略,我们今天就一起来看看MySQL数据库优化中Group BY 语句、 Order By语句 等。

优化GROUP BY语句

默认情况下,MySQL对所有GROUP BY col1,col2...的字段进行排序。这与在查询中指定ORDER BY col1,col2...类似。因此,如果显式包括一个包含相同的列的ORDER BY子句,则对MySQL的实际执行性能没有什么影响。 如果查询包括GROUP BY 但用户想要避免排序结果的消耗,则可以指定ORDER By NULL禁止排序,例如:

引用

<ol class="dp-xml">
<li class="alt"><span><span>explain select id, sum(moneys) from sales2 group by id \G   </span></span></li>
<li><span>explain select id, sum(moneys) from sales2 group by id order by null \G  </span></li>
</ol>


你可以通过比较发现第一条语句会比第二句在Extra:里面多了Using filesort.而恰恰filesort是最耗时的。

MySQL数据库优化ORDER BY语句

在某些情况中,MySQL可以使用一个索引来满足ORDER BY子句,而不需要额外的排序。WHERE 条件和 ORDER BY使用相同的索引,并且ORDER BY的顺序和索引顺序相同,并且ORDER BY的字段都是升序或者都是降序。

例如:

引用

<ol class="dp-xml">
<li class="alt"><span><span>SELECT * FROM t1 ORDER BY key_part1,key_part2,....:   </span></span></li>
<li>
<span>SELECT * FROM t1 WHERE </span><span class="attribute">key_part1</span><span> = 1 ORDER BY key_part1 DESC,key_part2 DESC;   </span>
</li>
<li class="alt"><span>SELECT * FROM t1 ORDER BY key_part1 DESC, key_part2 DESC;  </span></li>
</ol>

但是以下的情况不使用索引:

引用

<ol class="dp-xml"><li class="alt"><span><span>SELECT * FROM t1 ORDER BY key_part1 DESC, key_part2 ASC;  </span></span></li></ol>

ORDER by的字段混合ASC 和 DESC

<ol class="dp-xml"><li class="alt"><span><span>SELECT * FROM t1 WHERE </span><span class="attribute">key2</span><span>=</span><span class="attribute-value">constant</span><span> ORDER BY key1;  </span></span></li></ol>

用于查询行的关键字与ORDER BY 中所使用的不相同

<ol class="dp-xml"><li class="alt"><span><span>SELECT * FROM t1 ORDER BY key1, key2;  </span></span></li></ol>

对不同的关键字使用ORDER BY

MySQL数据库优化嵌套查询

MySQL4.1开始支持SQL的子查询。这个技术可以使用SELECT语句来创建一个单列的查询结果,然后把这个查询结果作为过滤条件用在另一个查询中,使用子查询可以一次性地完成多逻辑上需要多个步骤才能完成的SQL操作,同时也可以避免事务或者表锁死,并且些起来也很容易。但是,有些情况下,子查询可以被更有效的连接(JOIN)替代。
例如:

引用

<ol class="dp-xml">
<li class="alt"><span><span>explain select * from sales2 where company_id not in(select id from company2) \G   </span></span></li>
<li>
<span>explain select * from sales2 left join comany2 on </span><span class="attribute">sales2.company_id</span><span> = <br></span><span class="attribute-value">company2</span><span>.id where sales2.company_id is null \G;   </span>
</li>
</ol>


第一句看起来比第二句更简洁,但是第二句比第一就更快。因为使用JOIN来完成这个查询,速度比较快,尤其如果对compay2表中的id建立了索引的话,那么性能将会更好。那为什么在这种情况下使用JOIN会更有效率呢。因为MySQL不需要在内存中创建临时表来完成这个逻辑上需要两个步骤的查询工作。

优化OR条件

对于含有OR的查询子句,如果要利用索引,则OR之间的每个条件列都必须用到索引;如果没有索引,则考虑增加索引。

使用SQL提示

SQL 提示(SQL HINT)是MySQL数据库优化数据库的一个重要手段,简单来说就是在SQL语句中加入一些人为的提示来达到优化的操作的目的。
例如:

引用

<ol class="dp-xml"><li class="alt"><span><span>SELECT SQL_BUFFER_RESULTS * FROM ...  </span></span></li></ol>

这个语句将强制MySQL生成一个临时结果集。只要临时结果集生成后,所有表上的锁定均被释放。这能在遇到表锁定问题时或者要花很长时间将结果传给客户端时所帮助,因为可以尽快释放锁资源,

下面是一些在MySQL中常用的SQL提示。

引用

1. USE INDEX
在查询语句中表名的后面,添加USE INDEX 来提供希望MySQL去参考的索引列表,就可以让MySQL不再考虑其他可用的索引。

引用

<ol class="dp-xml"><li class="alt"><span><span>explain select * from sales2 use index (ind_sales2_id) where id 3 \G;  </span></span></li></ol>

2. IGNORE INDEX

如果用户只是单纯地想让MySQL忽略一个或者多个索引,则可以使用IGNORE INDEX 作为HINT

3. FORCE INDEX

为强制MySQL使用一个特定的索引,可在查询中使用FORCE INDEX作为HINT。例如当不强制使用索引的时候,因为id的值都是大于0的,因为MySQL会默认进行全表扫描,而不使用索引。例如:

引用

<ol class="dp-xml"><li class="alt"><span><span>expalin select * from sales2 where id </span><span class="tag">></span><span> 0 \G;  </span></span></li></ol>

但是,当使用FORCE INDEX进行提示时,即便使用索引的效率不是很高,MySQL还是选择使用了索引,这是MySQL留给用户的一个自行选择执行计划的权利。加入FORCE INDEX提示后在执行上面的SQL

引用

<ol class="dp-xml"><li class="alt"><span><span>explain select * from sales2 force index(index_sales2_id) where id </span><span class="tag">></span><span> 0 \G;  </span></span></li></ol>



 


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
When should you use a composite index versus multiple single-column indexes?When should you use a composite index versus multiple single-column indexes?Apr 11, 2025 am 12:06 AM

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

Describe MySQL asynchronous master-slave replication process.Describe MySQL asynchronous master-slave replication process.Apr 10, 2025 am 09:30 AM

MySQL asynchronous master-slave replication enables data synchronization through binlog, improving read performance and high availability. 1) The master server record changes to binlog; 2) The slave server reads binlog through I/O threads; 3) The server SQL thread applies binlog to synchronize data.

MySQL: Simple Concepts for Easy LearningMySQL: Simple Concepts for Easy LearningApr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL: A User-Friendly Introduction to DatabasesMySQL: A User-Friendly Introduction to DatabasesApr 10, 2025 am 09:27 AM

The installation and basic operations of MySQL include: 1. Download and install MySQL, set the root user password; 2. Use SQL commands to create databases and tables, such as CREATEDATABASE and CREATETABLE; 3. Execute CRUD operations, use INSERT, SELECT, UPDATE, DELETE commands; 4. Create indexes and stored procedures to optimize performance and implement complex logic. With these steps, you can build and manage MySQL databases from scratch.

How does the InnoDB Buffer Pool work and why is it crucial for performance?How does the InnoDB Buffer Pool work and why is it crucial for performance?Apr 09, 2025 am 12:12 AM

InnoDBBufferPool improves the performance of MySQL databases by loading data and index pages into memory. 1) The data page is loaded into the BufferPool to reduce disk I/O. 2) Dirty pages are marked and refreshed to disk regularly. 3) LRU algorithm management data page elimination. 4) The read-out mechanism loads the possible data pages in advance.

MySQL: The Ease of Data Management for BeginnersMySQL: The Ease of Data Management for BeginnersApr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.