MySQL的explain之type

一、準備

1.創建表

創建clazz和student表

create table clazz (
	cid int,
	cname varchar(20)
);

create table student(
	sid int,
	sname varchar(20),
	cid int
);

2.創建索引

student表爲sid創建唯一索引,爲sname和cid創建普通索引

clazz表爲cid創建唯一索引

create unique index idx_stu_sid on student(sid);
create index idx_stu_sname on student(sname);
create index idx_stu_cid on student(cid);
create unique index idx_cla_sid on clazz(cid);

3.插入數據

insert into clazz(cid, cname) values (1, 'clazz1'),(2, 'clazz2'),(3, 'clazz3');
insert into student(sid, sname, cid) values(1,'s1',1),(2,'s2',1),(3,'s3',1),
(4,'s4',2),(5,'s5',2),(6,'s6',2);

二、type類型

type顯示的是訪問類型,是較爲重要的一個指標,結果值從最好到最壞依次是:

system>const>eq_ref>ref>fulltext>ref_or_null>index_merge>unique_subquery>index_subquery>range>index>ALL

三、常見類型

常見的有:system>const>eq_ref>ref>range>index>ALL

一般來說,得保證查詢至少達到range級別,最好能達到ref

1.system

system:表只有一行記錄(等於系統表),這是const類型的特列,平時不會出現,這個也可以忽略不計

2.const

const:查找條件是主鍵或者唯一,並且只匹配一行數據,意味着不用往下掃描了

3.eq_ref

eq_ref:唯一性索引掃描,對於每個索引鍵,表中只有一條記錄與之匹配。常見於主鍵或唯一索引掃描

4.ref

ref:查找條件使用了索引,並且不是主鍵或唯一

5.range

range:查找條件使用了索引,值是個範圍(beween、>等)

6.index

index:這種連接類型只是另外一種形式的全表掃描,只不過它的掃描是按照索引的順序,all是沿着磁盤掃描,index是沿着索引掃描

索引覆蓋:查詢的值就是索引的值,不用掃描表

7.ALL

ALL:Full Table Scan,將遍歷全表以找到匹配的行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章