Home Database Mysql Tutorial Mysql -- 执行计划介绍_MySQL

Mysql -- 执行计划介绍_MySQL

Jun 01, 2016 pm 01:12 PM
Skill database programmer plan

一、序言

       作为程序员,难免要和数据库打交道,一般情况下,我们不是DBA ,但是又要写很多SQL,因此SQL效率就成了很大的问题。关于SQL效率优化,除了要掌握一定优化技巧外, 还得有很多经验的积累,但是这里我们可以通过执行计划对SQL进行分析,能快速找到优化的地方,这是一种很不错的方式,介绍给大家,大部分我是翻译而来,原文地址:http://dev.mysql.com/doc/refman/5.6/en/explain-output.html

二、执行计划输出列的含义:

    

Column Meaning
id The SELECT identifier
select_type The SELECT type
table The table for the output row
partitions The matching partitions
type The join type
possible_keys The possible indexes to choose
key The index actually chosen
key_len The length of the chosen key
ref The columns compared to the index
rows Estimate of rows to be examined
filtered Percentage of rows filtered by table condition
Extra Additional information

● id

   查询的标识,表示在select 执行语句中的顺序(PS:数字越大,优先执行)。如果这行是和其他行合并的结果,这个值可以为null。比如:使用 UNION 关键字,将多个select 的结果合并到一起。

● select_type:每个select 的类型。

select_typeMeaning
SIMPLE 简单的 SELECT (没有 使用UNION 或者 子查询(PS:单表查询))
PRIMARY 最外层的Select 作为primary 查询。(PS:含有子查询的情况,但是并不复杂)
UNION 从第二个或者在union 之后的select 作为 union 查询
DEPENDENT UNION 从第二个或者在union 之后的select 作为 union 查询, 依赖于外部查询
UNION RESULT 结果集是通过union 而来的,作为...
SUBQUERY 第一个查询是子查询
DEPENDENT SUBQUERY 第一个查询是子查询,依赖于外部查询
DERIVED 在from 查询语句中的(派生,嵌套很多)子查询.(PS:递归操作这些子查询)
MATERIALIZED (雾化) 子查询(PS:子查询是个视图?)
UNCACHEABLE SUBQUERY 子查询结果不能被缓存, 而且必须重写(分析)外部查询的每一行
UNCACHEABLE UNION 第二个 或者 在UNION 查询之后的select ,属于不可缓存的查询

● Table:输出所用到的表(PS:通过id 联系) 

● Type:连接类型,很重要的分析手段,下面按最优到最差排序:

   System:表只有一行(=系统表),const 的特例

   const:表查询结果最多只有一行,因为只有一行,该查询优化部分一般是常数。比如根据主键id=1 查询。

   比如:

SELECT * FROM tbl_name WHERE primary_key=1;
Copy after login

   eq_ref:从当前这个表读出的一行,和前面所有表的行进行组合,这是除了const 和system 外,最好的连接类型,它是用于所有的都是用唯一索引去连接被主键或者不为空的索引。常用=操作符比较索引

    比如:

    

SELECT * FROM ref_table,other_table WHERE ref_table.key_column=other_table.column;
Copy after login

   ref:用于连接非唯一索引的扫描。可以对索引的列使用> = 的操作符。

    比如: 

SELECT * FROM ref_table WHERE key_column=expr; SELECT * FROM ref_table,other_table WHERE ref_table.key_column=other_table.column;
Copy after login

     

SELECT * FROM <code style="font-size: 14px; background-color: #ffffff;">ref_table</code>,<code style="font-size: 14px; background-color: #ffffff;">other_table</code>WHERE <code>ref_table</code>.<code>key_column_part1</code>=<code>other_table</code>.<code>column</code>AND <code>ref_table</code>.<code>key_column_part2</code>=1;
Copy after login

    

     fulltext: 该方式使用的是全文检索

       ref or null : 该连接方式像ref,但是包含null 的值 ,该连接类型主要是解决子查询

       比如:

SELECT * FROM ref_table WHERE key_column=expr OR key_column IS NULL;
Copy after login

    index_merge:索引合并优化(PS:多个索引条件情况,进行条件的合并优化)

      

我版本低,没出现。。,可以参考下面解释:http://dev.mysql.com/doc/refman/5.6/en/index-merge-optimization.htmlSELECT * FROM tbl_name WHERE key1 = 10 OR key2 = 20;SELECT * FROM tbl_nameWHERE (key1 = 10 OR key2 = 20) AND non_key=30;SELECT * FROM t1, t2WHERE (t1.key1 IN (1,2) OR t1.key2 LIKE 'value%')AND t2.key1=t1.some_col;SELECT * FROM t1, t2WHERE t1.key1=1AND (t2.key1=t1.some_col OR t2.key2=t1.some_col2);
Copy after login

   

    unique_subquery:这个参照ref,处理子查询

    比如:

value IN (SELECT primary_key FROM single_table WHERE some_expr)
Copy after login

   index_subquery:这个和unique_subquery 类似,取代非唯一索引的子查询

    比如:

value IN (SELECT key_column FROM single_table WHERE some_expr)
Copy after login

   range:只有在range 范围内的都被检索,只用索引才查询哪些行。后面Key 表示你用的那个索引:

    比如:

    

SELECT * FROM tbl_nameWHERE key_column = 10;SELECT * FROM tbl_nameWHERE key_column BETWEEN 10 and 20;SELECT * FROM tbl_nameWHERE key_column IN (10,20,30);SELECT * FROM tbl_nameWHERE key_part1 = 10 AND key_part2 IN (10,20,30);
Copy after login

    

   index:这索引连接类型和ALL一样,除了树的索引扫描,分为两种情况: 1.会便利索引树,2.没有索引树,就是ALL 一样。

     All:全表扫描,通常是最差的一种查询。

● Extra:包含mysql 解析查询的额外信息。

   Distinct:mysql 查询不同的行,当找到和当前行匹配的时候,就不再搜索了。

   FirstMatch(tbl_name) :The semi-join FirstMatch join shortcutting strategy is used for tbl_name.  

   Full scan on NULL key:查询分析器无法使用当前索引的一个失败策略。

   Impossible HAVING: where 条件总是false,无法筛选任何行

   Impossible WHERE noticed after reading const tables:和上面类似

   LooseScan:利用索引来扫描一个子查询表可以从每个子查询的值群组中选出一个单一的值。

   Not exists:mysql 优化了left join 的查询,

   比如:

   

SELECT * FROM t1 LEFT JOIN t2 ON t1.id=t2.id WHERE t2.id IS NULL;假设t2.id 定义为 not null,这种情况下,Mysql 扫描t1 并且用t1.id 在t2中查找行,如果Mysql 在t2中找到匹配的行,它表明t2.id 不可能为null,因此不会扫描剩下的具有相同id的行,换句话说,t1 中的每一行,mysql 每次都在t2中做一下查询,无论t2 有多少匹配。
Copy after login

   

    Using filesort:无法利用索引完成的排序,比如文件排序

    Using index:利用索引树扫描得出结果,不用全部扫描

    Using temporary:利用临时表存储结果集,通常查询包含 GROUP BY and ORDER BY 。

     Using where:使用where 限定那些行于下一张表匹配,或者返回到客户端,除非你想要获取or 检查表中所有行,如果extra 的值不是Using where并且连接类型不是all 或者index ,那么你可能有一些错误在你的查询中。

    Using join buffer:

    Using MRR:有点复杂,

    参考:http://dev.mysql.com/doc/refman/5.6/en/mrr-optimization.html

    和:http://blog.csdn.net/zbszhangbosen/article/details/7463394

● Key:key 这一列表明实际你用的是那一个索引,没有则是null

● Key len:该列是Mysql 使用key 的长度,没有则为null,文档提示这值能确定你 multiple-part key  中使用的是哪一部分。

● Rows:表示Mysql 执行语句扫描的行数

● Possible_keys:表示mysql 找到的这些行数据,在indexes(很多索引)里面的哪一个。查询涉及到的字段上若存在索引,则该索引将被列出,但不一定被查询使用。如果是空的,没有相关的索引。这时要提高性能,可通过检验WHERE子句,看是否引用某些字段,或者检查字段不是适合索引。

小结:

        1.这个不得不吐槽,翻译太烂了...以至于后面都是自己的理解弄的,建议都去看原文啊,而且5.6+ 变化挺多,有些变化我也没遇到过,请见谅啊。

        2.这些简单的说明呢,仅仅是给大家提供一种分析SQL 的途径,也提醒大家不要盲目的根据SQL 去判断效率,当然你经验丰富,就不说啦~。~新手学习。

        3.如果你需要更详细的可以用show profile 的东西,能看到更详细的信息,精确度也更高,还有关于一些实战方面的应用,没来得及总结,这个以后再介绍吧。

        4.还是请见谅下,不正确的 狗血的地方请指出哦,谢谢啦。

        最后分享个不错的mysql 地址:

        http://www.mysqlab.net/

        http://www.mysqlpub.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)

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

A must-have for veterans: Tips and precautions for * and & in C language A must-have for veterans: Tips and precautions for * and & in C language Apr 04, 2024 am 08:21 AM

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How does Hibernate implement polymorphic mapping? How does Hibernate implement polymorphic mapping? Apr 17, 2024 pm 12:09 PM

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

Huawei P70 directly starts the Pioneer Plan and is officially on sale Huawei P70 directly starts the Pioneer Plan and is officially on sale Apr 19, 2024 pm 01:58 PM

Zhongguancun News: On the morning of April 18, Huawei suddenly announced that the P70 series of mobile phones are officially on sale under the Pioneer Plan. Friends who want to buy should be prepared to take action. According to past practice, Huawei's flagship mobile phones are very popular and will always be out of stock. . This time the Huawei P70 series has been renamed Pura, which means pure. Previously, Huawei's Yu Chengdong said: Since 2012, Huawei's P series smartphones have been like loyal partners, accompanying hundreds of millions of users around the world to spend countless precious moments and jointly witness the beauty and excitement of life. He deeply felt that the trust and love given by every user who chooses Huawei's P series is tantamount to a powerful driving force, always inspiring Huawei to move forward firmly on the road of innovation. Pura means pure.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

An in-depth analysis of how HTML reads the database An in-depth analysis of how HTML reads the database Apr 09, 2024 pm 12:36 PM

HTML cannot read the database directly, but it can be achieved through JavaScript and AJAX. The steps include establishing a database connection, sending a query, processing the response, and updating the page. This article provides a practical example of using JavaScript, AJAX and PHP to read data from a MySQL database, showing how to dynamically display query results in an HTML page. This example uses XMLHttpRequest to establish a database connection, send a query and process the response, thereby filling data into page elements and realizing the function of HTML reading the database.

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

See all articles