在使用MySQL進行查詢優化的時候,常常需要生成執行計劃文件進行分析和優化。下面介紹一下如何利用MySQL來生成執行計劃文件。
1. 打開MySQL客戶端,并連接到相應的數據庫。
$ mysql -h localhost -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 14 Server version: 5.7.20-0ubuntu0.16.04.1 (Ubuntu) mysql>
2. 運行使用EXPLAIN關鍵字的SQL查詢語句。
mysql>EXPLAIN SELECT * FROM employees WHERE salary >50000;
3. 查看執行計劃文件。
mysql>SHOW WARNINGS; +---------+------+-----------------------------------------------------+ | Level | Code | Message | +---------+------+-----------------------------------------------------+ | Warning | 1681 | 'NO_INDEX_USED' is deprecated and will be removed in | | | | a future release. Please use 'NO_INDEX' instead | | Warning | 1681 | 'NO_INDEX_USED' is deprecated and will be removed in | | | | a future release. Please use 'NO_INDEX' instead | +---------+------+-----------------------------------------------------+ mysql>SHOW EXPLAIN; +----+-------------+-----------+------+---------------+------+---------+------+------+----------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-----------+------+---------------+------+---------+------+------+----------+-------------+ | 1 | SIMPLE | employees | ALL | NULL | NULL | NULL | NULL | 18 | 100.00 | Using where | +----+-------------+-----------+------+---------------+------+---------+------+------+----------+-------------+
4. 將執行計劃文件輸出到文件中。
mysql>EXPLAIN SELECT * FROM employees WHERE salary >50000\G >/tmp/plan_file.txt
5. 查看輸出的執行計劃文件。
$ cat /tmp/plan_file.txt *************************** 1. row *************************** id: 1 select_type: SIMPLE table: employees partitions: NULL type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 18 filtered: 100.00 Extra: Using where 1 row in set, 1 warning (0.00 sec)
通過上述步驟,我們就可以很方便地生成MySQL的執行計劃文件。這對于進行查詢優化以及性能分析非常有幫助。