MySQL 要調整 SQL 語法最常使用的就是 EXPLAIN,不過這是看預測,要看實際的詳細運行時間,可以怎麼做呢?
MySQL 追蹤調校 Profiling SQL 詳細花費時間
想要看各個 SQL 語法細部使用的時間,可以使用 Profiling 來追蹤,詳見:13.7.5.31 SHOW PROFILE Statement
- 註:此語法適用 MySQL 5.6 以前的版本
MySQL Profiling 語法範例
- mysql> SELECT @@profiling; # 查看看是否有啟用,1:啟用、0:未啟用
- mysql> SET profiling = 1; # 啟用
- mysql> select ... # 多下幾個籲法
- mysql> SHOW PROFILES; 看每個 SQL 語法花多少時間
- mysql> SHOW PROFILE FOR QUERY 1;
- mysql> SHOW PROFILE FOR QUERY 2;
- mysql> SHOW PROFILE CPU FOR QUERY 2;
- mysql> SET profiling = 0; # 停止
不過現在都建議改用下述做法:
詳見:MySQL :: MySQL 5.6 Reference Manual :: 21.3.17 The INFORMATION_SCHEMA PROFILING Table
- SELECT STATE, FORMAT(DURATION, 6) AS DURATION FROM INFORMATION_SCHEMA.PROFILING WHERE QUERY_ID = 2 ORDER BY SEQ;
- SELECT * FROM INFORMATION_SCHEMA.PROFILING ORDER BY SEQ;
- SELECT * FROM INFORMATION_SCHEMA.PROFILING ORDER BY SEQ LIMIT 1 \G
MySQL 5.7 以後都用這個取代 profiling
詳見:MySQL :: MySQL 5.7 Reference Manual :: 25.19.1 Query Profiling Using Performance Schema
- 初始化設定
- SELECT * FROM performance_schema.setup_actors;
- UPDATE performance_schema.setup_actors SET ENABLED = 'NO', HISTORY = 'NO' WHERE HOST = '%' AND USER = '%';
- INSERT INTO performance_schema.setup_actors (HOST,USER,ROLE,ENABLED,HISTORY) VALUES('localhost','test_user','%','YES','YES');
- 再來就是另外設定哪些 SQL 要進 Profiling,這些在自行看上述文件即可