Mysql多列索引 最左精確匹配

2021-07-26 13:56:57 字數 1465 閱讀 4210

若mysql的一張表上有乙個多列索引,那麼在編寫where條件時,究竟哪些真正起到作用了呢,跟順序有關係嗎?

本文參考(

假設有如下的一張表:

drop table if exists testtable;

create table testtable

(id bigint not null auto_increment comment 'auto increment id',

host_name varchar(64) not null comment 'host name',

port varchar(64) not null comment 'port',

type int not null comment 'node type: actual or container',

launch_date date not null comment 'launch date',

modified timestamp not null comment 'modified time',

created timestamp not null comment 'created time',

primary key(id),

unique key index_worker_node(host_name,port,launch_date,type)

)comment='db workerid assigner for uid generator',engine = innodb;

對應的查詢語句分別是:

select * from testtable where port=3306 and type=1

select * from testtable where port=3307 and host_name='172.21.1.1'

select * from testtable where port=3308 and host_name='172.21.1.2' and type=2

那麼究竟用到了哪些索引呢?

第一句:沒用到索引

第二句:用到了輔助索引index_worker_node;

第三句:用到了輔助索引index_worker_node,但是只有host_name和port條件是通過索引完成的,條件type是依次掃瞄過濾完成的;

為什麼呢?

精確匹配(即"="和"in")

。不過順序倒是可以顛倒,因為查詢優化器重排序一下就好了。

回頭來看,第一句,由於缺少host_name,只能在聚集索引的葉節點上,從左至右的掃瞄,挨個比對;

第二句,可以直接在輔助索引上查詢,被找到的子樹的所有葉節點就是命中的記錄;

第三句,缺少launch_date條件,所以只能先依據host_name和prot在輔助索引上查詢,找到的主鍵值作為候選記錄,然後到聚集索引上讀取對應記錄,再比較type條件是否滿足。

mysql 最左匹配 聯合索引

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

MySQL索引 最左匹配原則

表結構,有三個字段,分別是id,name,cid create table student id int 11 not null auto increment,name varchar 255 default null,cid int 11 default null,primary key id k...

mysql 最左匹配 聯合索引

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