Analyzing Query Execution with MySQL EXPLAIN
MySQL 的 EXPLAIN 是用于分析查询执行计划的工具,通过在 SELECT 查询前加 EXPLAIN 可查看执行过程。1. 主要字段包括 id、select_type、table、type、key、Extra 等;2. 高效查询需关注 type(如 const、eq_ref 为佳)、key(是否使用合适索引)和 Extra(避免 Using filesort、Using temporary);3. 常见优化建议:避免对字段使用函数或模糊前导通配符、确保字段类型一致、合理设置连接字段索引、优化排序与分组操作,以提升性能并减少资源消耗。
MySQL 的 EXPLAIN
是一个非常实用的工具,能帮助我们理解查询是如何执行的,进而优化 SQL 性能。简单来说,它会告诉你 MySQL 是如何访问表、使用了哪些索引、有没有全表扫描等问题。

1. EXPLAIN 的基本用法
在你想分析的 SELECT
查询前面加上 EXPLAIN
,就能看到执行计划。例如:

EXPLAIN SELECT * FROM users WHERE id = 1;
执行后会返回一张表,里面包含了多个字段,比如 type
、key
、rows
等,这些信息就是你判断查询效率的关键。
常见字段说明:

- id:查询中每个 select 的唯一标识
- select_type:查询类型(如 SIMPLE、PRIMARY)
- table:当前查询操作涉及的表
- type:连接类型,常见的有 ALL、index、range、ref、eq_ref、const/system
- possible_keys:可能使用的索引
- key:实际使用的索引
- key_len:使用的索引长度
- ref:显示索引的哪一列被使用
- rows:MySQL 认为执行查询需要扫描的行数
- Extra:额外信息,如 Using filesort、Using temporary 等
2. 如何通过 EXPLAIN 判断查询是否高效
关键是要看几个核心字段:type
、key
和 Extra
。
type 字段:
- 最好是
const
或eq_ref
,表示走主键或唯一索引查找 ref
也不错,表示非唯一索引匹配range
表示用了索引范围扫描,还算可以- 如果是
index
,说明扫描了整个索引树,比全表扫描好一点 - 最差的是
ALL
,也就是全表扫描,一定要避免
- 最好是
key 字段:
- 看有没有使用到合适的索引,如果没有用索引,就要考虑加索引或者调整查询语句
Extra 字段:
- 出现
Using filesort
或Using temporary
通常意味着性能问题,尤其是大数据量时 Using where
是正常的,表示使用了 where 条件过滤数据
- 出现
举个例子:
EXPLAIN SELECT name FROM users WHERE email LIKE '%@example.com';
如果这里没有索引,而且 email
字段也没有前缀索引,那 type
就会是 ALL
,Extra
可能出现 Using where
,说明进行了全表扫描和条件过滤,效率不高。
3. 实际应用中的常见问题与优化建议
没有用上索引的情况
- 使用函数或表达式导致索引失效,例如
WHERE YEAR(create_time) = 2023
- 使用
LIKE
带通配符开头,例如LIKE '%abc'
- 类型不匹配,比如字段是
VARCHAR
,传入的是数字,可能导致隐式转换
建议:
- 避免在 where 子句中对字段做运算或函数处理
- 能用等值查询就不用模糊查询
- 注意字段类型一致性,避免隐式转换
多表关联时的问题
- 连接顺序不合理
- 关联字段没有索引
- join 类型是 ALL 或 index,而不是 ref 或 eq_ref
建议:
- 给经常用来做连接的字段加上索引
- 控制 join 表的数量,一般不超过 5 张表
- 查看执行计划中每张表的 type 是否合理
排序和分组性能差
- 使用了
ORDER BY
或GROUP BY
但没走索引 - 数据量大时出现
Using filesort
或Using temporary
建议:
- 对排序字段加复合索引
- 尽量避免不必要的排序或分组
- 分页时注意 limit 不要过大,避免内存压力
基本上就这些。用 EXPLAIN 分析 SQL 执行计划,其实并不难,关键是多练、多看、多对比。很多时候慢查询不是因为语句写错了,而是因为没有走索引,或者走了错误的索引。只要掌握了这几个关键点,排查和优化效率就会高很多。
The above is the detailed content of Analyzing Query Execution with MySQL EXPLAIN. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To add a primary key to an existing table, use the ALTERTABLE statement with the ADDPRIMARYKEY clause. 1. Ensure that the target column has no NULL value, no duplication and is defined as NOTNULL; 2. The single-column primary key syntax is ALTERTABLE table name ADDPRIMARYKEY (column name); 3. The multi-column combination primary key syntax is ALTERTABLE table name ADDPRIMARYKEY (column 1, column 2); 4. If the column allows NULL, you must first execute MODIFY to set NOTNULL; 5. Each table can only have one primary key, and the old primary key must be deleted before adding; 6. If you need to increase it yourself, you can use MODIFY to set AUTO_INCREMENT. Ensure data before operation

B-TreeindexesarebestformostPHPapplications,astheysupportequalityandrangequeries,sorting,andareidealforcolumnsusedinWHERE,JOIN,orORDERBYclauses;2.Full-Textindexesshouldbeusedfornaturallanguageorbooleansearchesontextfieldslikearticlesorproductdescripti

Using mysqldump is the most common and effective way to back up MySQL databases. It can generate SQL scripts containing table structure and data. 1. The basic syntax is: mysqldump-u[user name]-p[database name]>backup_file.sql. After execution, enter the password to generate a backup file. 2. Back up multiple databases with --databases option: mysqldump-uroot-p--databasesdb1db2>multiple_dbs_backup.sql. 3. Back up all databases with --all-databases: mysqldump-uroot-p

You can customize the separator by using the SEPARATOR keyword in the GROUP_CONCAT() function; 1. Use SEPARATOR to specify a custom separator, such as SEPARATOR'; 'The separator can be changed to a semicolon and plus space; 2. Common examples include using the pipe character '|', space'', line break character '\n' or custom string '->' as the separator; 3. Note that the separator must be a string literal or expression, and the result length is limited by the group_concat_max_len variable, which can be adjusted by SETSESSIONgroup_concat_max_len=10000; 4. SEPARATOR is optional

UNIONremovesduplicateswhileUNIONALLkeepsallrowsincludingduplicates;1.UNIONperformsdeduplicationbysortingandcomparingrows,returningonlyuniqueresults,whichmakesitsloweronlargedatasets;2.UNIONALLincludeseveryrowfromeachquerywithoutcheckingforduplicates,

The table can be locked manually using LOCKTABLES. The READ lock allows multiple sessions to read but cannot be written. The WRITE lock provides exclusive read and write permissions for the current session and other sessions cannot read and write. 2. The lock is only for the current connection. Execution of STARTTRANSACTION and other commands will implicitly release the lock. After locking, it can only access the locked table; 3. Only use it in specific scenarios such as MyISAM table maintenance and data backup. InnoDB should give priority to using transaction and row-level locks such as SELECT...FORUPDATE to avoid performance problems; 4. After the operation is completed, UNLOCKTABLES must be explicitly released, otherwise resource blockage may occur.

To select data from MySQL table, you should use SELECT statement, 1. Use SELECTcolumn1, column2FROMtable_name to obtain the specified column, or use SELECT* to obtain all columns; 2. Use WHERE clause to filter rows, such as SELECTname, ageFROMusersWHEREage>25; 3. Use ORDERBY to sort the results, such as ORDERBYageDESC, representing descending order of age; 4. Use LIMIT to limit the number of rows, such as LIMIT5 to return the first 5 rows, or use LIMIT10OFFSET20 to implement paging; 5. Use AND, OR and parentheses to combine

TheINoperatorinMySQLchecksifavaluematchesanyinaspecifiedlist,simplifyingmultipleORconditions;itworkswithliterals,strings,dates,andsubqueries,improvesqueryreadability,performswellonindexedcolumns,supportsNOTIN(withcautionforNULLs),andcanbecombinedwith
