使用mysql的PROFILE功能 我們可以查看一個SQL執行的代價是什麼情況,PROFILE功能只能在SESSION級別使用,所以我們可以根據以下SQL來進行查詢:
mysql> SELECT @@profiling;
+-------------+
| @@profiling |
+-------------+
| 0 |
+-------------+
1 row in set
mysql> SET profiling = 1;
Query OK, 0 rows affected
mysql> select * from ab_test;
#查詢的數據 由於條數太多 我刪除了
mysql> show profiles;
+----------+----------+-----------------------+
| Query_ID | Duration | Query |
+----------+----------+-----------------------+
| 1 | 0.032328 | select * from ab_test |
+----------+----------+-----------------------+
1 row in set
mysql> SHOW PROFILE;
+----------------------+----------+
| Status | Duration |
+----------------------+----------+
| starting | 0.005237 |
| checking permissions | 0.001638 |
| Opening tables | 0.006219 |
| init | 0.001662 |
| System lock | 0.001489 |
| optimizing | 0.001576 |
| statistics | 0.001422 |
| preparing | 0.001285 |
| executing | 0.001313 |
| Sending data | 0.001618 |
| end | 0.001362 |
| query end | 0.001569 |
| closing tables | 0.001689 |
| freeing items | 0.002667 |
| cleaning up | 0.001585 |
+----------------------+----------+
15 rows in set
mysql> SHOW PROFILE FOR QUERY 1;
+----------------------+----------+
| Status | Duration |
+----------------------+----------+
| starting | 0.005237 |
| checking permissions | 0.001638 |
| Opening tables | 0.006219 |
| init | 0.001662 |
| System lock | 0.001489 |
| optimizing | 0.001576 |
| statistics | 0.001422 |
| preparing | 0.001285 |
| executing | 0.001313 |
| Sending data | 0.001618 |
| end | 0.001362 |
| query end | 0.001569 |
| closing tables | 0.001689 |
| freeing items | 0.002667 |
| cleaning up | 0.001585 |
+----------------------+----------+
15 rows in set
mysql> SHOW PROFILE CPU
FOR QUERY 1;
+----------------------+----------+----------+------------+
| Status | Duration | CPU_user | CPU_system |
+----------------------+----------+----------+------------+
| starting | 0.005237 | 0.005 | 0 |
| checking permissions | 0.001638 | 0 | 0.002999 |
| Opening tables | 0.006219 | 0.006999 | 0 |
| init | 0.001662 | 0.000999 | 0.001 |
| System lock | 0.001489 | 0 | 0.001 |
| optimizing | 0.001576 | 0 | 0.002 |
| statistics | 0.001422 | 0 | 0.000999 |
| preparing | 0.001285 | 0 | 0.003 |
| executing | 0.001313 | 0 | 0 |
| Sending data | 0.001618 | 0 | 0.002 |
| end | 0.001362 | 0 | 0.001 |
| query end | 0.001569 | 0 | 0.001999 |
| closing tables | 0.001689 | 0.003 | 0 |
| freeing items | 0.002667 | 0.002999 | 0.001 |
| cleaning up | 0.001585 | 0 | 0.001 |
+----------------------+----------+----------+------------+
15 rows in set
mysql>
其中SHOW PROFILE 的用法官網可以查詢,官網PROFILE教程詳解:
SHOW PROFILE [type [, type] ... ]
[FOR QUERY n]
[LIMIT row_count [OFFSET offset]]
type: {
ALL
| BLOCK IO
| CONTEXT SWITCHES
| CPU
| IPC
| MEMORY
| PAGE FAULTS
| SOURCE
| SWAPS
}
通過這些查詢我們可以確定SQL執行的效率 也爲更好的優化打下基礎