簡述MySQL聯合索引最左匹配原則

2021-10-04 12:10:08 字數 1758 閱讀 5028

在網上看過一些有關最左匹配原則的部落格,自以為自己理解了,但是今天面試的時候被面試官深挖了一下,就暴露了其實並沒有真正理解到最左匹配原則。

mysql在建立聯合索引的時候,會從左到右依次建立遞增的索引。而且也比較推薦建立聯合索引,因為乙個索引可以起到很多個索引的作用。

create

table

`index_test`

(`id`

int(11)

notnull

auto_increment

,`a`

int(11)

default

null

,`b`

int(11)

default

null

,`c`

int(11)

default

null

,primary

key(

`id`),

key`index_abc`

(`a`

,`b`

,`c`))

engine

=innodb

default

charset

=utf8mb4 collate

=utf8mb4_0900_ai_ci

聯合索引index_a_b_c實際上相當於建立了三個索引,(a),(a,b),(a,b,c)這麼一來,索引是按照a -> b -> c的排序方式形成b+樹,可以使用a and b and c依次走a b c 的索引,如果是搜尋a and c的話只走了a索引,可以走聯合索引的情況有:

# 單個

select

*from test where a =1;

# 多個

select

*from test where a =

1and b =1;

select

*from test where a =

1and b =

1and c =1;

# 注意(a,c)其實也是有索引的

select

*from test where a =

1and c =1;

# 在sql解析器看來都一樣

select

*from test where a =

1and b =1;

select

*from test where b =

1and a =

1;

對於聯合索引(a,b,c),查詢語句select * from test where b = 1,是否能夠觸發索引?

大多數人都會說no,實際上確實yes。

使用explain工具查詢的時候,經常會看兩種索引:

type:index

type:ref

index:這種型別表示mysql會對整個索引進行掃瞄。這種檢索方式的使用條件是,只要是索引,或者搜尋的內容是索引的一部分,都可以觸發。mysql會採用掃瞄整個索引的方式來查詢,缺點就是效率不高。

ref:這種型別表示mysql會根據特定的演算法來找到符合條件的資料。而不是對整個索引進行遍歷,也就是平常理解對使用索引可以快速找到資料的原因。但是這種檢索方式也是有條件的,索引必須符合滿足條件的資料結構,也就是說索引必須是有序的,才可以使用這種檢索方式。

mysql 最左匹配 聯合索引

mysql建立多列索引 聯合索引 有最左字首的原則,即最左優先,如 如果有乙個2列的索引 col1,col2 則已經對 col1 col1,col2 上建立了索引 如果有乙個3列索引 col1,col2,col3 則已經對 col1 col1,col2 col1,col2,col3 上建立了索引 總...

mysql 最左匹配 聯合索引

mysql建立多列索引 聯合索引 有最左字首的原則,即最左優先,如 如果有乙個2列的索引 col1,col2 則已經對 col1 col1,col2 上建立了索引 如果有乙個3列索引 col1,col2,col3 則已經對 col1 col1,col2 col1,col2,col3 上建立了索引 總...

Mysql 聯合索引最左匹配原則

二 測試現象 drop table if exists test table create table test table id int 11 not null auto increment comment 編號 namee varchar 255 default null comment 姓名 ...