Explain關鍵字詳解

2021-10-20 21:03:58 字數 3518 閱讀 4713

使用explain關鍵字可以模擬優化器執行sql語句,分析你的查詢語句或是結構的效能瓶頸 在 select 語句之前增加 explain 關鍵字,mysql 會在查詢上設定乙個標記,執行查詢會返回執行計畫的資訊,而不是執行這條sql 像這樣

create table actor

(id int primary key auto_increment,

name varchar(10

),create_time datetime

) engine=innodb default charset=utf8;

insert into actor

(name,create_time)

values

('a'

,now()

),('b'

,now()

),('c'

,now()

);

create table film

(id int primary key auto_increment,

name varchar(10

)default null,

index idx_name (name)

) engine=innodb default charset=utf8;

insert into film

(name)

values

('film0'),

('film1'),

('film2'

);

create table film_actor

(id int primary key auto_increment,

film_id int not null,

actor_id int not null,

key idx_fild_actor_id (film_id,actor_id)

) engine=innodb default charset=utf8;

insert into film_actor ( film_id, actor_id) values (1,

1),(

1,2)

,(2,1);

id列的編號是 select 的序列號,有幾個 select 就有幾個id,並且id的順序是按 select 出現的順序增長的。 id列越大執行優先順序越高,id相同則從上往下執行,id為null最後執行。
select_type 表示對應行是簡單還是複雜的查詢。

(1) ******:簡單查詢。查詢不包含子查詢和union

(2) primary:複雜查詢中最外層的 select

(3) subquery:包含在 select 中的子查詢(不在 from 子句中)

(4) derived:包含在 from 子句中的子查詢。mysql會將結果存放在乙個臨時表中,也稱為派生表(derived的英文含義)

表示訪問的哪一張表, 如果是的格式,說明當前查詢依賴id=n的查詢,於是先執行id=n的查詢;
表示當前的查詢或連線型別,即mysql決定如何查詢表中的記錄;

依次從最優到最差為:system-->const-->eq_ref-->ref-->range-->index-->all

system,const: mysql 查詢時能夠將查詢條件優化成常量,並且走primary key 或者unique key ,整張表中只可能查詢出一條資料;

eq_ref: 在進行連線查詢或者子查詢時 primary key 或 unique key 索引的所有字段;

ref: 進行查詢時,只使用normal 或 primary key 或 unique 中的部分索引;

range: 通常出現在能夠走索引的範圍查詢;

index:掃瞄全索引就能拿到結果值, 一般是利用二級索引,使用索引覆蓋;

all :全表掃瞄, 掃瞄聚簇索引的所有葉子節點;

可能會使用到的索引;
實際使用到的索引:
使用到索引的長度,  一般以索引的資料型別長度為準, 如 int 4位元組,  double 8位元組,  字串 varchar, char 與字符集有關, utf8情況下 char(n)= 3n, 

varchar(n)=3n+2 加的2位元組用來儲存字串長度,因為varchar是變長字串; 如果字段允許為null,還需要 1 位元組來記錄;

這一列顯示了在key列記錄的索引中,表查詢值所用到的列或常量,常見的有:const(常量),欄位名(例:film.id)
這一列是mysql估計要讀取並檢測的行數,注意這個不是結果集裡的行數。
這一列展示的是額外資訊。常見的重要值如下:

1)using index:使用覆蓋索引 覆蓋索引定義:mysql執行計畫explain結果裡的key有使用索引,如果select後面查詢的字段都可以從這個索引的樹中 獲取,這種情況一般可以說是用到了覆蓋索引,extra裡一般都有using index;覆蓋索引一般針對的是輔助索引,整個 查詢結果只通過輔助索引就能拿到結果,不需要通過輔助索引樹找到主鍵,再通過主鍵去主鍵索引樹里獲取其它字段值

2)using where:使用 where 語句來處理結果,並且查詢的列未被索引覆蓋

3)using index condition:查詢的列不完全被索引覆蓋,where條件中是乙個前導列的範圍;

4)using temporary:mysql需要建立一張臨時表來處理查詢。出現這種情況一般是要進行優化的,首先是想到用索 引來優化。

mysql之explain關鍵字

1 用mysql儲存過程增加100萬條測試資料 儲存過程 建立儲存過程,資料庫名test,表名student create procedure myinst n int begin declare i int default0 set autocommit 0 repeat set i i 1 in...

MySQL 中 explain關鍵字

select 查詢的序列號,包含一組數字,表示查詢中執行 select 子句或操作表的順序。三種情況 id 相同 執行順序由上而下 from t1,t2,t3 where t1.id t2.id and t1.id t3.id and t1.other column from t2 where id...

MySQL 優化之 EXPLAIN 關鍵字

mysql查詢優化之explain的深入解析 首先執行如下的 sql 語句 create table ifnot exists article id int 10 unsigned not null auto increment,author id int 10 unsigned not null,...