Home Database Mysql Tutorial [慢查优化]慎用MySQL子查询,尤其是看到DEPENDENT SUBQUERY标倒

[慢查优化]慎用MySQL子查询,尤其是看到DEPENDENT SUBQUERY标倒

Jun 07, 2016 pm 04:15 PM
mysql optimization Inquire

[慢查优化]慎用MySQL子查询,尤其是看到DEPENDENT SUBQUERY标记时 案例梳理时间:2013-9-25 写在前面的话: 在慢查优化1和2里都反复强调过 explain 的重要性,但有时候肉眼看不出 explain 结果如何指导优化,这时候还需要有一些其他基础知识的佐助, 甚至需要

[慢查优化]慎用MySQL子查询,尤其是看到DEPENDENT SUBQUERY标记时
案例梳理时间:2013-9-25
写在前面的话:
  1. 在慢查优化1和2里都反复强调过 explain 的重要性,但有时候肉眼看不出 explain 结果如何指导优化,这时候还需要有一些其他基础知识的佐助,甚至需要了解 MySQL 实现原理,如子查询慢查优化
  2. 看到 SQL 执行计划中 select_type 字段中出现“DEPENDENT SUBQUERY”时,要打起精神了!

——MySQL 的子查询为什么有时候很糟糕——

引子:这样的子查询为什么这么慢?

下面的例子是一个慢查,线上执行时间相当夸张。为什么呢?

SELECT gid,COUNT(id) as count?

FROM shop_goods g1

WHERE status =0 and gid IN (?

SELECT gid FROM shop_goods g2 WHERE sid IN ?(1519066,1466114,1466110,1466102,1466071,1453929)

)

GROUP BY gid;

它的执行计划如下,请注意看关键词“DEPENDENT SUBQUERY”:

??? id? select_type???????? table?? type??????????? possible_keys?????????????????????????? key?????????? key_len? ref?????? rows? Extra???? ?
------? ------------------? ------? --------------? --------------------------------------? ------------? -------? ------? ------? -----------
???? 1? PRIMARY???????????? g1????? index?????????? (NULL)????????????????????????????????? idx_gid? 5??????? (NULL)? 850672? Using where
???? 2? DEPENDENT SUBQUERY? g2????? index_subquery? id_shop_goods,idx_sid,idx_gid? idx_gid? 5??????? func???????? 1? Using where

?

基础知识:Dependent Subquery意味着什么

官方含义为:

SUBQUERY:子查询中的第一个SELECT;

DEPENDENT SUBQUERY:子查询中的第一个SELECT,取决于外面的查询

换句话说,就是?子查询对 g2 的查询方式依赖于外层 g1 的查询

什么意思呢?它意味着两步:

第一步,MySQL 根据?select gid,count(id) from shop_goods where?status=0 group by gid;?得到一个大结果集 t1,其数据量就是上图中的 rows=850672 了。

第二步,上面的大结果集 t1 中的每一条记录,都将与子查询 SQL 组成新的查询语句:select gid from shop_goods where sid in (15...blabla..29) and gid=%t1.gid%。等于说,子查询要执行85万次……即使这两步查询都用到了索引,但不慢才怪。

如此一来,子查询的执行效率居然受制于外层查询的记录数,那还不如拆成两个独立查询顺序执行呢

?

优化策略1:

你不想拆成两个独立查询的话,也可以与临时表联表查询,如下所示:

SELECT g1.gid,count(1)

FROM shop_goods g1,(select gid from shop_goods WHERE sid in (1519066,1466114,1466110,1466102,1466071,1453929)) g2

where g1.status=0 and?g1.gid=g2.gid

GROUP BY g1.gid;

也能得到同样的结果,且是毫秒级。

它的执行计划为:

??? id? select_type? table?????????? type??? possible_keys????????????? key??????????? key_len? ref??????????? rows? Extra???????????????????????? ?
------? -----------? --------------? ------? -------------------------? -------------? -------? -----------? ------? -------------------------------
???? 1? PRIMARY????? ????? ALL???? (NULL)???????????????????? (NULL)???????? (NULL)?? (NULL)?????????? 30? Using temporary; Using filesort
???? 1? PRIMARY????? g1????????????? ref???? idx_gid?????????????? idx_gid?? 5??????? g2.gid?????? 1? Using where?????????????????? ?
???? 2? DERIVED????? shop_goods? range?? id_shop_goods,idx_sid? id_shop_goods? 5??????? (NULL)?????????? 30? Using where; Using index??????

DERIVED 的官方含义为:

DERIVED:用于 from 子句里有子查询的情况。MySQL 会递归执行这些子查询,把结果放在临时表里。

?

DBA观点引用:MySQL 子查询的弱点

hidba 论述道(参考资源3):

mysql 在处理子查询时,会改写子查询。

通常情况下,我们希望由内到外,先完成子查询的结果,然后再用子查询来驱动外查询的表,完成查询。

例如:

select * from test where tid in(select fk_tid from sub_test where gid=10)

通常我们会感性地认为该 sql 的执行顺序是:

sub_test 表中根据 gid 取得 fk_tid(2,3,4,5,6)记录,

然后再到 test 中,带入 tid=2,3,4,5,6,取得查询数据。

但是实际mysql的处理方式为:

select * from test where exists (

select * from sub_test where gid=10 and sub_test.fk_tid=test.tid

)

mysql 将会扫描 test 中所有数据,每条数据都将会传到子查询中与 sub_test 关联,子查询不会先被执行,所以如果 test 表很大的话,那么性能上将会出现问题。

?

《高性能MySQL》一书的观点引用

《高性能MySQL》的第4.4节“MySQL查询优化器的限制(Limitations of the MySQL Query Optimizer)”之第4.4.1小节“关联子查询(Correlated Subqueries)”也有类似的论述:

MySQL有时优化子查询很糟,特别是在WHERE从句中的IN()子查询。……

比如在sakila数据库sakila.film表中找出所有的film,这些film的actoress包括Penelope Guiness(actor_id = 1)。可以这样写:

mysql> SELECT * FROM sakila.film

-> WHERE film_id IN(

-> SELECT film_id FROM sakila.film_actor WHERE actor_id = 1);

mysql> EXPLAIN SELECT * FROM sakila.film ...;

+----+--------------------+------------+--------+------------------------+

| id | select_type ? ? ? ?| table ? ? ?| type ? | possible_keys ? ? ? ? ?|

+----+--------------------+------------+--------+------------------------+

| 1 ?| PRIMARY ? ? ? ? ? ?| film ? ? ? | ALL ? ?| NULL ? ? ? ? ? ? ? ? ? |

| 2 ?|?DEPENDENT SUBQUERY?| film_actor | eq_ref | PRIMARY,idx_fk_film_id |

+----+--------------------+------------+--------+------------------------+

根据EXPLAIN的输出,MySQL将全表扫描film表,对找到的每行执行子查询,这是很不好的性能。幸运的是,很容易改写为一个join查询:

mysql> SELECT film.* FROM sakila.film

-> INNER JOIN sakila.film_actor USING(film_id)

-> WHERE actor_id = 1;

另外一个方法是通过使用GROUP_CONCAT()执行子查询作为一个单独的查询,手工产生IN()列表。有时候比join还快。(注:你不妨在我们的库上试试看?SELECT goods_id,GROUP_CONCAT(cast(id as char))

FROM bee_shop_goods

WHERE shop_id IN (1519066,1466114,1466110,1466102,1466071,1453929)

GROUP BY goods_id;)

MySQL已经因为这种特定类型的子查询执行计划而被批评。

?

何时子查询是好的

MySQL并不总是把子查询优化得很糟。有时候还是很优化的。下面是个例子:

mysql> EXPLAIN SELECT film_id, language_id FROM sakila.film

-> WHERE NOT EXISTS(

-> SELECT * FROM sakila.film_actor

-> WHERE film_actor.film_id = film.film_id

-> )G

……(注:具体文字还是请阅读《高性能MySQL》吧)

是的,子查询并不是总是被优化得很糟糕,具体问题具体分析,但别忘了 explain 。

?

参考资源:

1,2011,wudongxu,mysql子查询(in)的实现;

2,2012,iteye,MySQL子查询很慢的问题;

3,2011,hidba,mysql子查询的弱点?和?生产库中遇到mysql的子查询;


慢查系列:

[慢查优化]建索引时注意字段选择性 & 范围查询注意组合索引的字段顺序

[慢查优化]联表查询注意谁是驱动表 & 你搞不清楚谁join谁更好时请放手让mysql自行判定


赠图几枚:

/img/2013/12/08/230619118.jpg

@易度-潘俊勇: 许式伟的这个ppt,涵盖了他所有对golang的理解,推荐大家阅读: http://t.cn/zRI8tIH

/img/2013/12/08/230619119.jpg

/img/2013/12/08/230619120.jpg

?

-over-

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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

How to use MySQL backup and restore in PHP? How to use MySQL backup and restore in PHP? Jun 03, 2024 pm 12:19 PM

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to insert data into a MySQL table using PHP? How to insert data into a MySQL table using PHP? Jun 02, 2024 pm 02:26 PM

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values ​​to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How to use MySQL stored procedures in PHP? How to use MySQL stored procedures in PHP? Jun 02, 2024 pm 02:13 PM

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

How to create a MySQL table using PHP? How to create a MySQL table using PHP? Jun 04, 2024 pm 01:57 PM

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

C++ program optimization: time complexity reduction techniques C++ program optimization: time complexity reduction techniques Jun 01, 2024 am 11:19 AM

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

The difference between oracle database and mysql The difference between oracle database and mysql May 10, 2024 am 01:54 AM

Oracle database and MySQL are both databases based on the relational model, but Oracle is superior in terms of compatibility, scalability, data types and security; while MySQL focuses on speed and flexibility and is more suitable for small to medium-sized data sets. . ① Oracle provides a wide range of data types, ② provides advanced security features, ③ is suitable for enterprise-level applications; ① MySQL supports NoSQL data types, ② has fewer security measures, and ③ is suitable for small to medium-sized applications.

See all articles