CREATE TABLE `user2` ( `userid` INT (11) NOT NULL AUTO_INCREMENT, `username` VARCHAR (20) NOT NULL DEFAULT '', `password` VARCHAR (20) NOT NULL DEFAULT '', `usertype` VARCHAR (20) NOT NULL DEFAULT '', PRIMARY KEY (`userid`), KEY `a_b_c_index` ( `username`, `password`, `usertype` ) ) ENGINE = INNODB AUTO_INCREMENT = 2 DEFAULT CHARSET = utf8;
上表中有一个联合索引,下面开始验证最左匹配原则。
当存在username时会使用索引查询:
explain select * from user2 where username = '1' and password = '1';

Paste_Image.png
当没有username时,不会使用索引查询:explain select * from user2 where password = '1';

Paste_Image.png
当有username,但顺序乱序时也可以使用索引:
explain select * from user2 where password = '1' and username = '1';

Paste_Image.png
在最左匹配原则中,有如下说明:
- 最左前缀匹配原则,非常重要的原则,mysql会一直向右匹配直到遇到范围查询(>、<、between、like)就停止匹配,比如a = 1 and b = 2 and c > 3 and d = 4 如果建立(a,b,c,d)顺序的索引,d是用不到索引的,如果建立(a,b,d,c)的索引则都可以用到,a,b,d的顺序可以任意调整。
- =和in可以乱序,比如a = 1 and b = 2 and c = 3 建立(a,b,c)索引可以任意顺序,mysql的查询优化器会帮你优化成索引可以识别的形式