Home Database Mysql Tutorial MySQL查询语句执行过程及性能优化-查询过程及优化方法(JOIN/ORD_MySQL

MySQL查询语句执行过程及性能优化-查询过程及优化方法(JOIN/ORD_MySQL

Jun 01, 2016 pm 01:29 PM
mysql

bitsCN.com

MySQL查询语句执行过程及性能优化-查询过程及优化方法(JOIN/ORDER BY)

 

[plain] mysql> explain select user.Username, user_profile.nickname, user_profile.gender, user_profile.meet_receive from user_profile join users on users.Id = user_profile.user_id where user_profile.`display` = '1' order by user_profile.fl_no limit 50;
Copy after login
+----+-------------+---------------------+--------+---------------+---------+---------+----------------------------------------+-------+----------------------------------------------+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |+----+-------------+---------------------+--------+---------------+---------+---------+----------------------------------------+-------+----------------------------------------------+| 1 | SIMPLE | user_profile | ALL | NULL | NULL | NULL | NULL | 14399 | Using where; Using temporary; Using filesort || 1 | SIMPLE | users | eq_ref | PRIMARY | PRIMARY | 8 | icbd_cmsdb.user_profile.user_id | 1 | Using where |+----+-------------+---------------------+--------+---------------+---------+---------+----------------------------------------+-------+----------------------------------------------+2 rows in set (0.00 sec)

可以看到上述的查询需要检查1万多记录,并且使用了临时表和filesort排序,这样的查询在用户数快速增长后将成为噩梦。

在优化这个语句之前,我们先了解下SQL查询的基本执行过程:

*)应用通过MySQL API把查询命令发送给MySQL服务器,然后被解析

*)检查权限、MySQL optimizer进行优化,经过解析和优化后的查询命令被编译为CPU可运行的二进制形式的查询计划(query plan),并可以被缓存

*)如果存在索引,那么先扫描索引,如果数据被索引覆盖,那么不需要额外的查找,如果不是,根据索引查找和读取对应的记录

*)如果有关联查询,查询次序是扫描第一张表找到满足条件的记录,按照第一张表和第二张表的关联键值,扫描第二张表查找满足条件的记录,按此顺序循环

*)输出查询结果,并记录binary logs

显然合适的索引将大大简化和加速查找。再看一下上面那条查询语句,除了条件查询外,还有关联查询以及ORDER BY即排序操作,

那么让我们进一步了解下关联查询(JOIN)和ORDER BY是怎么工作的,MySQL有三种方式来处理关联查询和数据排序:

[plain] 方法<strong>                                                      </strong>EXPLAIN结果显示  Use index-based access method that produces ordered output        不会出现filesort  Use filesort() on 1st non-constant table                          &ldquo;Using filesort&rdquo;出现在第一行Extra中  Put join result into a temporary table and use filesort() on it       &ldquo;Using temporary; Using filesort&rdquo;出现在第一行Extra中  
Copy after login

第一种方法是基于索引,第二种是对第一个非常量表进行filesort(quicksort),还有一种是把联合查询的结果放入临时表,然后进行filesort。

filesort有两种模式:

1、模式1:排序后的元素涵盖了要输出的数据。排序结果是一串有序序列元素组,不再需要额外的记录读取;

2、模式2:排序结果是键值对序列,通过这些row_ids再去读取记录(随机读取,效率低下);

第一种方法用于第一个非常量表中存在ORDER BY所依赖的列的索引,那就可直接使用已经有序的索引来查找关联表的数据,这种方式是性能最优的,因为不需要额外的排序动作:

MySQL查询语句执行过程及性能优化-查询过程及优化方法(JOIN/ORD_MySQL

第二种方式用于ORDER BY所依赖的列全部属于第一张查询表且没有索引,那么我们可以先对第一张表的记录进行filesort(模式可能是模式1也可能是模式2),得到有序行索引,然后再做关联查询,filesort的结果可能是在内存中,也可能在硬盘上,这取决于系统变量sort_buffer_size(一般为2M左右):

MySQL查询语句执行过程及性能优化-查询过程及优化方法(JOIN/ORD_MySQL

第三种方法用于当ORDER BY的元素不属于第一张表时,需要把关联查询的结果放入临时表,最后对临时表进行filesort:

MySQL查询语句执行过程及性能优化-查询过程及优化方法(JOIN/ORD_MySQL

第三种方法中的临时表,可能是在内存中(in-memory table),也可能是在硬盘上,一般是下面两种情况会使用硬盘(on-disk table):

(1)使用了BLOB,TEXT类型的数据

(2)内存表占用超过了系统变量tmp_table_size/max_heap_table_size的限定(一般为16M左右),只能放在硬盘上

从上面的查询执行过程和方式,我们应该可以清楚的知道为什么Using filesort,Using temporary会严重的影响查询性能,因为如果数据类型或者字段设计有问题,

在需要查询的表以及结果中存在大数据的字段,而没有合适的索引可用时,都可能会导致产生大量的IO操作,这就是查询性能缓慢的根源所在。

回到文章开头所举的查询实例,它显然是使用了效率最低的第三种方法,我们需要做和尝试的优化手段有:

1、为users.fl_no添加索引,为select和where所使用的字段建立索引

2、把users.fl_no转移到或者作为冗余字段添加到表user_profile中

3、去除TEXT类型的字段,TEXT可以替换为VARCHAR(65535)或对于中文而言VARCHAR(20000)

4、如果实在无法消除Using filesort,那么提高sort_buffer_size,以减少IO操作负担

5、尽量使用第一张表所覆盖的索引进行排序,实在不行,可以把排序逻辑从MySQL中移到PHP/Java程序中执行

实施1、2、3的优化方法后,EXPLAIN结果如下:

[plain] mysql> explain select user.Username, user_profile.nickname, user_profile.gender, user_profile.meet_receive from user_profile join users on users.Id = user_profile.user_id where user_profile.`display` = &#39;1&#39; order by user_profile.fl_no limit 50;  +----+-------------+---------------+--------+---------------+---------+---------+---------------------------------+------+--------------------------+  | id | select_type | table         | type   | possible_keys | key     | key_len | ref                             | rows | Extra                    |  +----+-------------+---------------+--------+---------------+---------+---------+---------------------------------+------+--------------------------+  |  1 | SIMPLE      | user_profile1 | index  | NULL          | fl_no   | 4       | NULL                            |   50 | Using where              |  |  1 | SIMPLE      | users         | eq_ref | PRIMARY       | PRIMARY | 8       | slowquery.user_profile1.user_id |    1 | Using where              |  +----+-------------+---------------+--------+---------------+---------+---------+---------------------------------+------+--------------------------+  2 rows in set (0.00 sec)  
Copy after login

 

 

备注:编写简单的PHP应用,用siege测试,查询效率提高>3倍。

bitsCN.com
Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

See all articles