1. 程式人生 > >mysql 獲取執行計劃的方法

mysql 獲取執行計劃的方法

mysql 獲取執行計劃方法:
1.通過explain進行檢視sql的執行計劃;
2.通執行緒正在執行的sql檢視該sql的執行計劃;

  explain進行檢視sql的執行計劃相對簡單,其實通執行緒正在執行的sql檢視執行計劃也很簡單,那麼為什麼還需要第二種方式呢?

  因為日常工作會發現很多sql一直在執行,執行發生異常,如果把該sql拿出來執行又很快,於是我們想獲取該sql執行異常時候的執行計劃,同時因為資料在時刻的變化,統計資訊也有可能變化,有可能導致執行計劃發生改變,好在mysql5.7開始已經可以通過正在執行的執行緒檢視該sql的執行計劃,不需要把sql拿出來執行獲取執行計劃,這樣就可以很好的還原真相:

show processlist;或者select * from information_schema.PROCESSLIST where info is not null order by time desc ;檢視。

mysql> select from information_schema.PROCESSLIST where info is not null;
+-----+------+-----------------+------+---------+------+--------------+-----------------------------------------------------------------------+
| ID | USER | HOST | DB | COMMAND | TIME | STATE | INFO |
+-----+------+-----------------+------+---------+------+--------------+-----------------------------------------------------------------------+
| 17 | root | localhost | NULL | Query | 0 | executing | select

from information_schema.PROCESSLIST where info is not null |
| 178 | root | localhost:60124 | app1 | Query | 560 | Sending data | select count(*) from t ,t_adress where t.adress = t_adress.adress |
+-----+------+-----------------+------+---------+------+--------------+-----------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql> EXPLAIN FOR CONNECTION 178;
+----+-------------+----------+------------+------+---------------+------+---------+------+--------+----------+----------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+----------+------------+------+---------------+------+---------+------+--------+----------+----------------------------------------------------+
| 1 | SIMPLE | t_adress | NULL | ALL | NULL | NULL | NULL | NULL | 200096 | 100.00 | NULL |
| 1 | SIMPLE | t | NULL | ALL | NULL | NULL | NULL | NULL | 309664 | 100.00 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+----------+------------+------+---------------+------+---------+------+--------+----------+----------------------------------------------------+
2 rows in set (0.01 sec)

使用起來是不是很方便?