MySQL 的 EXPLAIN 是用于分析查詢執(zhí)行計(jì)劃的工具,通過在 SELECT 查詢前加 EXPLAIN 可查看執(zhí)行過程。1. 主要字段包括 id、select_type、table、type、key、Extra 等;2. 高效查詢需關(guān)注 type(如 const、eq_ref 為佳)、key(是否使用合適索引)和 Extra(避免 Using filesort、Using temporary);3. 常見優(yōu)化建議:避免對(duì)字段使用函數(shù)或模糊前導(dǎo)通配符、確保字段類型一致、合理設(shè)置連接字段索引、優(yōu)化排序與分組操作,以提升性能并減少資源消耗。
MySQL 的 EXPLAIN
是一個(gè)非常實(shí)用的工具,能幫助我們理解查詢是如何執(zhí)行的,進(jìn)而優(yōu)化 SQL 性能。簡(jiǎn)單來說,它會(huì)告訴你 MySQL 是如何訪問表、使用了哪些索引、有沒有全表掃描等問題。

1. EXPLAIN 的基本用法
在你想分析的 SELECT
查詢前面加上 EXPLAIN
,就能看到執(zhí)行計(jì)劃。例如:

EXPLAIN SELECT * FROM users WHERE id = 1;
執(zhí)行后會(huì)返回一張表,里面包含了多個(gè)字段,比如 type
、key
、rows
等,這些信息就是你判斷查詢效率的關(guān)鍵。
常見字段說明:

- id:查詢中每個(gè) select 的唯一標(biāo)識(shí)
- select_type:查詢類型(如 SIMPLE、PRIMARY)
- table:當(dāng)前查詢操作涉及的表
- type:連接類型,常見的有 ALL、index、range、ref、eq_ref、const/system
- possible_keys:可能使用的索引
- key:實(shí)際使用的索引
- key_len:使用的索引長(zhǎng)度
- ref:顯示索引的哪一列被使用
- rows:MySQL 認(rèn)為執(zhí)行查詢需要掃描的行數(shù)
- Extra:額外信息,如 Using filesort、Using temporary 等
2. 如何通過 EXPLAIN 判斷查詢是否高效
關(guān)鍵是要看幾個(gè)核心字段:type
、key
和 Extra
。
type 字段:
- 最好是
const
或eq_ref
,表示走主鍵或唯一索引查找 ref
也不錯(cuò),表示非唯一索引匹配range
表示用了索引范圍掃描,還算可以- 如果是
index
,說明掃描了整個(gè)索引樹,比全表掃描好一點(diǎn) - 最差的是
ALL
,也就是全表掃描,一定要避免
- 最好是
key 字段:
- 看有沒有使用到合適的索引,如果沒有用索引,就要考慮加索引或者調(diào)整查詢語(yǔ)句
Extra 字段:
- 出現(xiàn)
Using filesort
或Using temporary
通常意味著性能問題,尤其是大數(shù)據(jù)量時(shí) Using where
是正常的,表示使用了 where 條件過濾數(shù)據(jù)
- 出現(xiàn)
舉個(gè)例子:
EXPLAIN SELECT name FROM users WHERE email LIKE '%@example.com';
如果這里沒有索引,而且 email
字段也沒有前綴索引,那 type
就會(huì)是 ALL
,Extra
可能出現(xiàn) Using where
,說明進(jìn)行了全表掃描和條件過濾,效率不高。
3. 實(shí)際應(yīng)用中的常見問題與優(yōu)化建議
沒有用上索引的情況
- 使用函數(shù)或表達(dá)式導(dǎo)致索引失效,例如
WHERE YEAR(create_time) = 2023
- 使用
LIKE
帶通配符開頭,例如LIKE '%abc'
- 類型不匹配,比如字段是
VARCHAR
,傳入的是數(shù)字,可能導(dǎo)致隱式轉(zhuǎn)換
建議:
- 避免在 where 子句中對(duì)字段做運(yùn)算或函數(shù)處理
- 能用等值查詢就不用模糊查詢
- 注意字段類型一致性,避免隱式轉(zhuǎn)換
多表關(guān)聯(lián)時(shí)的問題
- 連接順序不合理
- 關(guān)聯(lián)字段沒有索引
- join 類型是 ALL 或 index,而不是 ref 或 eq_ref
建議:
- 給經(jīng)常用來做連接的字段加上索引
- 控制 join 表的數(shù)量,一般不超過 5 張表
- 查看執(zhí)行計(jì)劃中每張表的 type 是否合理
排序和分組性能差
- 使用了
ORDER BY
或GROUP BY
但沒走索引 - 數(shù)據(jù)量大時(shí)出現(xiàn)
Using filesort
或Using temporary
建議:
- 對(duì)排序字段加復(fù)合索引
- 盡量避免不必要的排序或分組
- 分頁(yè)時(shí)注意 limit 不要過大,避免內(nèi)存壓力
基本上就這些。用 EXPLAIN 分析 SQL 執(zhí)行計(jì)劃,其實(shí)并不難,關(guān)鍵是多練、多看、多對(duì)比。很多時(shí)候慢查詢不是因?yàn)檎Z(yǔ)句寫錯(cuò)了,而是因?yàn)闆]有走索引,或者走了錯(cuò)誤的索引。只要掌握了這幾個(gè)關(guān)鍵點(diǎn),排查和優(yōu)化效率就會(huì)高很多。
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)

1. The first choice for the Laravel MySQL Vue/React combination in the PHP development question and answer community is the first choice for Laravel MySQL Vue/React combination, due to its maturity in the ecosystem and high development efficiency; 2. High performance requires dependence on cache (Redis), database optimization, CDN and asynchronous queues; 3. Security must be done with input filtering, CSRF protection, HTTPS, password encryption and permission control; 4. Money optional advertising, member subscription, rewards, commissions, knowledge payment and other models, the core is to match community tone and user needs.

There are three main ways to set environment variables in PHP: 1. Global configuration through php.ini; 2. Passed through a web server (such as SetEnv of Apache or fastcgi_param of Nginx); 3. Use putenv() function in PHP scripts. Among them, php.ini is suitable for global and infrequently changing configurations, web server configuration is suitable for scenarios that need to be isolated, and putenv() is suitable for temporary variables. Persistence policies include configuration files (such as php.ini or web server configuration), .env files are loaded with dotenv library, and dynamic injection of variables in CI/CD processes. Security management sensitive information should be avoided hard-coded, and it is recommended to use.en

To achieve MySQL deployment automation, the key is to use Terraform to define resources, Ansible management configuration, Git for version control, and strengthen security and permission management. 1. Use Terraform to define MySQL instances, such as the version, type, access control and other resource attributes of AWSRDS; 2. Use AnsiblePlaybook to realize detailed configurations such as database user creation, permission settings, etc.; 3. All configuration files are included in Git management, support change tracking and collaborative development; 4. Avoid hard-coded sensitive information, use Vault or AnsibleVault to manage passwords, and set access control and minimum permission principles.

Why do I need SSL/TLS encryption MySQL connection? Because unencrypted connections may cause sensitive data to be intercepted, enabling SSL/TLS can prevent man-in-the-middle attacks and meet compliance requirements; 2. How to configure SSL/TLS for MySQL? You need to generate a certificate and a private key, modify the configuration file to specify the ssl-ca, ssl-cert and ssl-key paths and restart the service; 3. How to force SSL when the client connects? Implemented by specifying REQUIRESSL or REQUIREX509 when creating a user; 4. Details that are easily overlooked in SSL configuration include certificate path permissions, certificate expiration issues, and client configuration requirements.

To collect user behavior data, you need to record browsing, search, purchase and other information into the database through PHP, and clean and analyze it to explore interest preferences; 2. The selection of recommendation algorithms should be determined based on data characteristics: based on content, collaborative filtering, rules or mixed recommendations; 3. Collaborative filtering can be implemented in PHP to calculate user cosine similarity, select K nearest neighbors, weighted prediction scores and recommend high-scoring products; 4. Performance evaluation uses accuracy, recall, F1 value and CTR, conversion rate and verify the effect through A/B tests; 5. Cold start problems can be alleviated through product attributes, user registration information, popular recommendations and expert evaluations; 6. Performance optimization methods include cached recommendation results, asynchronous processing, distributed computing and SQL query optimization, thereby improving recommendation efficiency and user experience.

When choosing a suitable PHP framework, you need to consider comprehensively according to project needs: Laravel is suitable for rapid development and provides EloquentORM and Blade template engines, which are convenient for database operation and dynamic form rendering; Symfony is more flexible and suitable for complex systems; CodeIgniter is lightweight and suitable for simple applications with high performance requirements. 2. To ensure the accuracy of AI models, we need to start with high-quality data training, reasonable selection of evaluation indicators (such as accuracy, recall, F1 value), regular performance evaluation and model tuning, and ensure code quality through unit testing and integration testing, while continuously monitoring the input data to prevent data drift. 3. Many measures are required to protect user privacy: encrypt and store sensitive data (such as AES

PHP plays the role of connector and brain center in intelligent customer service, responsible for connecting front-end input, database storage and external AI services; 2. When implementing it, it is necessary to build a multi-layer architecture: the front-end receives user messages, the PHP back-end preprocesses and routes requests, first matches the local knowledge base, and misses, call external AI services such as OpenAI or Dialogflow to obtain intelligent reply; 3. Session management is written to MySQL and other databases by PHP to ensure context continuity; 4. Integrated AI services need to use Guzzle to send HTTP requests, safely store APIKeys, and do a good job of error handling and response analysis; 5. Database design must include sessions, messages, knowledge bases, and user tables, reasonably build indexes, ensure security and performance, and support robot memory

To enable PHP containers to support automatic construction, the core lies in configuring the continuous integration (CI) process. 1. Use Dockerfile to define the PHP environment, including basic image, extension installation, dependency management and permission settings; 2. Configure CI/CD tools such as GitLabCI, and define the build, test and deployment stages through the .gitlab-ci.yml file to achieve automatic construction, testing and deployment; 3. Integrate test frameworks such as PHPUnit to ensure that tests are automatically run after code changes; 4. Use automated deployment strategies such as Kubernetes to define deployment configuration through the deployment.yaml file; 5. Optimize Dockerfile and adopt multi-stage construction
