search
HomeDatabaseMysql TutorialMysql -- 执行计划介绍_MySQL

一、序言

       作为程序员,难免要和数据库打交道,一般情况下,我们不是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;

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

    比如:

    

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

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

    比如: 

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

     

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;

    

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

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

       比如:

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

    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);

   

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

    比如:

value IN (SELECT primary_key FROM single_table WHERE some_expr)

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

    比如:

value IN (SELECT key_column FROM single_table WHERE some_expr)

   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);

    

   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 有多少匹配。

   

    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
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
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

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

Video Face Swap

Video Face Swap

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

Hot Tools

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools