1. 程式人生 > 其它 >MySQL索引型別(type)分析

MySQL索引型別(type)分析

技術標籤:MySQL資料庫

type索引型別:

ststem > const > eq_ref > ref > range > index > all

  • 優化級別從左往右遞減,沒有索引的一般為’all’,需要對type進行優化前提是有索引。
  • 其中’system’和’const’只是理想型,實際只能達到’ref’和’range’。

注意:這裡主要針對MySQL5.6進行講解,與其他版本有區別,但是原理過程一致

建立兩張表teacher和teacherCard

# 教師表
create table teacher(
    tid int(5),
    tname varchar
(20), tcid int(5) ); # 教師卡 create table teacherCard( tcid int(5), tcdesc varchar(20) ); # 插入教師資訊 insert into teacher values(1, 'tz', 1); insert into teacher values(2, 'tw', 2); insert into teacher values(3, 'tl', 3); # 插入教師卡資訊 insert into teacherCard values(1, 'tzdesc'); insert into teacherCard values
(2, 'twdesc'); insert into teacherCard values(3, 'tldesc'); # 新增主鍵索引 alter table teacheradd constraint tid_pk primary key(tid);

1.system

衍生表只有一條資料的主查詢;衍生表通過主鍵查詢只有一條資料,再通過這條資料進行主查詢。

# 子查詢為主鍵查詢
explain select * from (select * from test01 where tid = 1) t;

子查詢通過主鍵查詢得出一條資料(該條資料構成衍生表),通過衍生表的資料進行主查詢,其衍生表的索引型別為system。

在這裡插入圖片描述

2.const

僅僅能查到一條資料的SQL,用於primary key 或 unique的索引(其他索引型別不屬於)。

# 主鍵查詢只有一條資料的情況,型別為const
explain select * from test01 where tid = 1;

在這裡插入圖片描述

3.eq_ref

唯一性索引,表索引與另外表的主鍵進行關聯,兩張表之間每條資料要一一對應(每個都要一一對應,不能一個對應多個,不能沒有對應),查詢的資料在表中是唯一性,不能有重複。

# 給teacherCard新增主鍵
alter table teacherCard add constraint pk_tcid primary key(tcid);

# 對teacher表進行索引唯一查詢
explain select t.tcid from teacher t, teacherCard tc where t.tcid = tc.tcid;

主表(沒有外來鍵的表)為eq_ref:
在這裡插入圖片描述

4.ref

非唯一線性索引,對於每個索引鍵的查詢返回的資料為0或多條。

# 給teacher表的tname的欄位新增索引
alter table teacher add index tname_index (tname);

# 根據tname = tz查詢出兩條資料
explain select * from teacher where tname = 'tz'; 

根據tname索引直接查詢出來的值為ref型別。
在這裡插入圖片描述

5.range

檢查指定範圍行,where後面是一個範圍查詢(between、in、>、<、=等)。

# 檢視range型別的索引
explain select * from teacher t where t.tid in (1, 2);
explain select * from teacher where tid between 1 and 2;
explain select * from teacher where tid < 3;

範圍查詢指定的索引,其索引型別為range:
在這裡插入圖片描述

6.index

查詢索引中的所有資料。

# 查詢索引的所有資料,其中tname就是索引
explain select tname from teacher;

在這裡插入圖片描述

7.all

查詢表中的所有資料,或者根據不是索引的欄位查詢。

# 直接查詢
explain select * from teacher;

type型別總結:

  • system/const:結果只有一條資料。
  • eq_ref:結果多條,但是每條資料都是唯一的。
  • ref:結果多條,但是查詢到的資料可以是多條,且資料可以重複。
  • range:根究索引欄位進行範圍查詢。

參考連結:https://www.bilibili.com/video/BV1es411u7we?p=9