Home Database Mysql Tutorial [慢查优化]联表查询注意哪位高手是驱动表 & 你搞不清楚

[慢查优化]联表查询注意哪位高手是驱动表 & 你搞不清楚

Jun 07, 2016 pm 04:14 PM
amp optimization Inquire Notice drive master

[慢查优化]联表查询注意谁是驱动表 你搞不清楚谁join谁更好时请放手让mysql自行判定 写在前面的话: ?? 不要求每个人一定理解 联表查询 (join/left join/inner join 等 ) 时的 mysql 运算过程; ??? 不要求每个人一定知道线上 (现在或未来) 哪张表数据量大

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

写在前面的话:

?? 不要求每个人一定理解 联表查询(join/left join/inner join)时的mysql运算过程;

???不要求每个人一定知道线上(现在或未来)哪张表数据量大,哪张表数据量小;

????但把mysql客户端(如SQLyog,如HeidiSQL)放在桌面上,时不时拿出来 explain 一把,这是一种美德


在实例讲解之前,我们先回顾一下联表查询的基础知识。

——联表查询的基础知识——

引子:为什么第一个查询using temporary,第二个查询不用临时表呢?

下面两个查询,它们只差了一个order by,效果却迥然不同。

第一个查询:

EXPLAIN extended

SELECT ads.id

FROM ads, city?

WHERE

? ?city.city_id = 8005

? ?AND ads.status = 'online'

? ?AND city.ads_id=ads.id

ORDER BY?ads.id?desc

执行计划为:

??? id? select_type? table?? type??? possible_keys?? key????? key_len? ref???????????????????? rows? filtered? Extra???????????????????????? ?
------? -----------? ------? ------? --------------? -------? -------? --------------------? ------? --------? -------------------------------
???? 1? SIMPLE?????? city??? ref???? ads_id,city_id? city_id? 4??????? const?????????????????? 2838??? 100.00? Using temporary; Using filesort
???? 1? SIMPLE?????? ads???? eq_ref? PRIMARY???????? PRIMARY? 4??????? city.ads_id?????? 1??? 100.00? Using where???????????????????

第二个查询:

EXPLAIN extended

SELECT ads.id

FROM ads,city?

WHERE

? ?city.city_id =8005

? ?AND ads.status = 'online'

? ?AND city.ads_id=ads.id

ORDER BY?city.ads_id?desc

执行计划里没有了using temporary: ??? id? select_type? table?? type??? possible_keys?? key????? key_len? ref???????????????????? rows? filtered? Extra???????????????????? ?
------? -----------? ------? ------? --------------? -------? -------? --------------------? ------? --------? ---------------------------
???? 1? SIMPLE?????? city??? ref???? ads_id,city_id? city_id? 4??????? const?????????????????? 2838??? 100.00? Using where; Using filesort
???? 1? SIMPLE?????? ads??? eq_ref? PRIMARY???????? PRIMARY? 4??????? city.ads_id?????? 1??? 100.00? Using where??????????????? 为什么? ? DBA告诉我们: ? ? MySQL 表关联的算法是 Nest Loop Join,是通过驱动表的结果集作为循环基础数据,然后一条一条地通过该结果集中的数据作为过滤条件到下一个表中查询数据,然后合并结果。 ? EXPLAIN 结果中,第一行出现的表就是驱动表(Important!) ? 以上两个查询语句,驱动表都是 city,如上面的执行计划所示! ? 对驱动表可以直接排序对非驱动表(的字段排序)需要对循环查询的合并结果(临时表)进行排序(Important!) 因此,order by ads.id desc 时,就要先 using temporary 了! ? 驱动表的定义 wwh999?在 2006年总结说,当进行多表连接查询时,?[驱动表]?的定义为:
1)指定了联接条件时,满足查询条件的记录行数少的表为[驱动表];
2)未指定联接条件时,行数少的表为[驱动表](Important!)。 ? 忠告:如果你搞不清楚该让谁做驱动表、谁 join 谁,请让 MySQL 运行时自行判断 既然“未指定联接条件时,行数少的表为[驱动表]”了, 而且你也对自己写出的复杂的 Nested Loop Join 不太有把握(如下面的实例所示), 就别指定谁 left/right join 谁了, 请交给 MySQL优化器 运行时决定吧。 如果您对自己特别有信心,可以像火丁一样做优化。 ? 小结果集驱动大结果集 de.cel?在2012年总结说,不管是你,还是 MySQL, 优化的目标是尽可能减少JOIN中Nested Loop的循环次数, 以此保证:
永远用小结果集驱动大结果集(Important!)

——实例讲解—— ? Nested Loop Join慢查SQL语句 先了解一下 mb 表有 千万级记录,mbei 表要少得多。慢查实例如下:
explain SELECT mb.id, …… FROMmb?LEFT JOIN mbei ON mb.id=mbei.mb_id?INNER JOINu ON mb.uid=u.uid ? WHERE 1=1 ? ORDER BY mbei.apply_time DESC limit 0,10
够复杂吧。Nested Loop Join 就是这样, 以驱动表的结果集作为循环的基础数据,然后将结果集中的数据作为过滤条件一条条地到下一个表中查询数据,最后合并结果;此时还有第三个表,则将前两个表的 Join 结果集作为循环基础数据,再一次通过循环查询条件到第三个表中查询数据,如此反复。 这条语句的执行计划如下: ??? id? select_type? table?? type??? possible_keys?? key???????????? key_len? ref???????????????????? rows? Extra????????????????????????????????????? ?
------? -----------? ------? ------? --------------? --------------? -------? -------------------? -------? --------------------------------------------
???? 1? SIMPLE?????? mb????? index?? userid????????? userid????????? 4??????? (NULL)?????????????? 6060455? Using index; Using temporary; Using filesort
???? 1? SIMPLE?????? mbei??? eq_ref? mb_id? mb_id? 4??????? mb.id???????????? 1???????????????????????????????????????????? ?
???? 1? SIMPLE?????? u?????? eq_ref? PRIMARY???????? PRIMARY???????? 4??????? mb.uid??????? 1? Using index???????????????????????????????? 由于动用了“LEFT JOIN”,所以攻城狮已经指定了驱动表,虽然这张驱动表的结果集记录数达到百万级! . . 如何优化? . . 优化第一步:LEFT JOIN改为JOIN 干嘛要 left join 啊?直接 join!
explain SELECT mb.id……
FROM mb?JOIN mbei ON mb.id=mbei.mb_id?INNER JOINu ON mb.uid=u.uid ? WHERE 1=1 ? ORDER BY mbei.apply_time DESC limit 0,10
立竿见影,驱动表立刻变为小表 mbei 了, Using temporary 消失了,影响行数少多了: ??? id? select_type? table?? type??? possible_keys?? key????? key_len? ref???????????????????????????? rows? Extra??????? ?
------? -----------? ------? ------? --------------? -------? -------? ----------------------------? ------? --------------
???? 1? SIMPLE?????? mbei??? ALL???? mb_id? (NULL)?? (NULL)?? (NULL)???????????????????????? 13383? Using filesort
???? 1? SIMPLE?????? mb????? eq_ref? PRIMARY,userid? PRIMARY? 4??????? mbei.mb_id?????? 1?????????????? ?
???? 1? SIMPLE?????? u?????? eq_ref? PRIMARY???????? PRIMARY? 4??????? mb.uid??????????????? 1? Using index??
优化第一步之分支1:根据驱动表的字段排序,好吗?
left join不变。干嘛要根据非驱动表的字段排序呢?我们前面说过“对驱动表可以直接排序,对非驱动表(的字段排序)需要对循环查询的合并结果(临时表)进行排序!”的。
explain SELECT mb.id……
FROM mb LEFT JOIN mbei ON mb.id=mbei.mb_id?INNER JOINu ON mb.uid=u.uid ? WHERE 1=1 ? ORDER BY?mb.id DESC limit 0,10
也满足业务场景,做到了rows最小: ??? id? select_type? table?? type??? possible_keys?? key???????????? key_len? ref??????????????????? rows? Extra???? ?
------? -----------? ------? ------? --------------? --------------? -------? -------------------? ------? -----------
???? 1? SIMPLE?????? mb????? index?? userid????????? PRIMARY???????? 4??????? (NULL)?????????????????? 10??????????? ?
???? 1? SIMPLE?????? mbei??? eq_ref? mb_id? mb_id? 4??????? mb.id??????????? 1? Using index
???? 1? SIMPLE?????? u?????? eq_ref? PRIMARY???????? PRIMARY???????? 4??????? mb.uid?????? 1? Using index ?
优化第二步:去除所有JOIN,让MySQL自行决定!
写这么多密密麻麻的 left join/inner join 很开心吗?
explain SELECT mb.id……
FROM mb,mbei,u? ?
WHERE
?? ?mb.id=mbei.mb_id
?? ?and mb.uid=u.user_id
order by mbei.apply_time desc
limit 0,10
立竿见影,驱动表一样是小表 mbei: ??? id? select_type? table?? type??? possible_keys?? key????? key_len? ref???????????????????????????? rows? Extra??????? ?
------? -----------? ------? ------? --------------? -------? -------? ----------------------------? ------? --------------
???? 1? SIMPLE?????? mbei??? ALL???? mb_id? (NULL)?? (NULL)?? (NULL)???????????????????????? 13388? Using filesort
???? 1? SIMPLE?????? mb????? eq_ref? PRIMARY,userid? PRIMARY? 4??????? mbei.mb_id?????? 1?????????????? ?
???? 1? SIMPLE?????? u?????? eq_ref? PRIMARY???????? PRIMARY? 4??????? mb.uid??????????????? 1? Using index??
最后的总结:
强调再强调:
不要过于相信你的运气! 不要相信你的开发环境里SQL的执行速度! 请拿起 explain 武器, 如果你看到以下现象,请优化:
  • 出现了Using temporary;
  • rows过多,或者几乎是全表的记录数;
  • key 是 (NULL);
  • possible_keys 出现过多(待选)索引。
? 记住,explain 是一种美德!
? ?
参考资源: 1)wwh999,2006,进行多表查时的排序问题,其多表查询时的原理论证!?; 2)de.cel,2012,MySQL中的Join 原理及优化思路?; 3)火丁,2013,MySQL优化的奇技淫巧之STRAIGHT_JOIN; ? 赠图一枚: /img/2013/10/18/113350732.gif
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
3 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)

Does Logitech ghub driver not support win7? -Why can Logitech ghub driver only be installed on the c drive? Does Logitech ghub driver not support win7? -Why can Logitech ghub driver only be installed on the c drive? Mar 18, 2024 pm 05:37 PM

Does Logitech ghub driver not support win7? Not compatible. Since Windows 7 has stopped updating and is no longer Microsoft's main operating system, many new software no longer supports it, such as Logitech ghub. The main interface of the Logitech driver: 1. The main software interface is on the left. The three buttons are lighting, buttons, and sensitivity settings. 2. In the settings of the lighting interface, the general special effects are relatively conventional, and the audio visual effects are the highlight. They can change color according to the sound frequency, and can be set according to the high, middle and bass bands, with different colors and effects. 3. In button settings, users can edit them here according to their special requirements. 4. In the sensitivity settings, many users will have some of their own settings. They can add the DPI speed switching point by themselves, but

How to check your academic qualifications on Xuexin.com How to check your academic qualifications on Xuexin.com Mar 28, 2024 pm 04:31 PM

How to check my academic qualifications on Xuexin.com? You can check your academic qualifications on Xuexin.com, but many users don’t know how to check their academic qualifications on Xuexin.com. Next, the editor brings you a graphic tutorial on how to check your academic qualifications on Xuexin.com. Interested users come and take a look! Xuexin.com usage tutorial: How to check your academic qualifications on Xuexin.com 1. Xuexin.com entrance: https://www.chsi.com.cn/ 2. Website query: Step 1: Click on the Xuexin.com address above to enter the homepage Click [Education Query]; Step 2: On the latest webpage, click [Query] as shown by the arrow in the figure below; Step 3: Then click [Login Academic Credit File] on the new page; Step 4: On the login page Enter the information and click [Login];

12306 How to check historical ticket purchase records How to check historical ticket purchase records 12306 How to check historical ticket purchase records How to check historical ticket purchase records Mar 28, 2024 pm 03:11 PM

Download the latest version of 12306 ticket booking app. It is a travel ticket purchasing software that everyone is very satisfied with. It is very convenient to go wherever you want. There are many ticket sources provided in the software. You only need to pass real-name authentication to purchase tickets online. All users You can easily buy travel tickets and air tickets and enjoy different discounts. You can also start booking reservations in advance to grab tickets. You can book hotels or special car transfers. With it, you can go where you want to go and buy tickets with one click. Traveling is simpler and more convenient, making everyone's travel experience more comfortable. Now the editor details it online Provides 12306 users with a way to view historical ticket purchase records. 1. Open Railway 12306, click My in the lower right corner, and click My Order 2. Click Paid on the order page. 3. On the paid page

How to install win11 driver without digital signature_Tutorial on how to deal with win11 driver without digital signature How to install win11 driver without digital signature_Tutorial on how to deal with win11 driver without digital signature Mar 20, 2024 pm 04:46 PM

Some users have encountered some problems when installing drivers for win11 computers. The computer prompts that the digital signature of this file cannot be verified, resulting in the inability to install the driver. How to solve this problem? Please see the following introduction for details. 1. Press the [Win + [Ctrl+Shift+Enter] Open the Windows Powershell window with administrator rights; 3. User Account Control window, do you want to allow this application to make changes to your device? Click [Yes]; 4. Administrator: Windows Powers

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.

Comparison of similarities and differences between MySQL and PL/SQL Comparison of similarities and differences between MySQL and PL/SQL Mar 16, 2024 am 11:15 AM

MySQL and PL/SQL are two different database management systems, representing the characteristics of relational databases and procedural languages ​​respectively. This article will compare the similarities and differences between MySQL and PL/SQL, with specific code examples to illustrate. MySQL is a popular relational database management system that uses Structured Query Language (SQL) to manage and operate databases. PL/SQL is a procedural language unique to Oracle database and is used to write database objects such as stored procedures, triggers and functions. same

How to check the latest price of Tongshen Coin? How to check the latest price of Tongshen Coin? Mar 21, 2024 pm 02:46 PM

How to check the latest price of Tongshen Coin? Token is a digital currency that can be used to purchase in-game items, services, and assets. It is decentralized, meaning it is not controlled by governments or financial institutions. Transactions of Tongshen Coin are conducted on the blockchain, which is a distributed ledger that records the information of all Tongshen Coin transactions. To check the latest price of Token, you can use the following steps: Choose a reliable price check website or app. Some commonly used price query websites include: CoinMarketCap: https://coinmarketcap.com/Coindesk: https://www.coindesk.com/ Binance: https://www.bin

Windows disables forced driver signature to solve the problem that individual device drivers cannot be installed normally. Windows disables forced driver signature to solve the problem that individual device drivers cannot be installed normally. Jun 19, 2024 am 07:22 AM

Driver signature, also called driver digital signature, is completed by Microsoft's Windows Hardware Device Quality Laboratory. Hardware developers submit their hardware devices and corresponding drivers to the laboratory, which will test them. After passing the test, the laboratory will add a digital signature to the driver. Since the digital signature is done by Microsoft. The computer needs to have the driver installed before it can be used normally. Sometimes it is found that the downloaded driver cannot be installed without a digital signature. This is because the system blocks the installation of uncertified drivers for security reasons. However, sometimes some special devices fail to pass the verification. driver, then obviously only by temporarily turning off digital signature can the installation be normal. Let’s take a look at how to disable driver signature enforcement

See all articles