数据库索引最左匹配原则
参考:https://blog.csdn.net/weixin_45969384/article/details/107597585
重点:
1.建立联合索引时会遵循最左匹配原则,即最左优先,在检索数据时从联合索引的最左边开始匹配
2.如果联合索引中最左边的列不在查询条件中,则不会命中索引
如
为user表中的name、address、phone列添加联合索引
ALTER TABLE user ADD INDEX index_three(name,address,phone);
所以,下面的三个SQL语句都可以命中索引,即使name不在第一个,也会自动做优化。
SELECT * FROM user WHERE address = ‘北京’ AND phone = ‘12345’ AND name = ‘张三’;
SELECT * FROM user WHERE name = ‘张三’ AND address = ‘北京’;
SELECT * FROM user WHERE name = ‘张三’;
但是,SELECT * FROM user WHERE address = ‘北京’ ,这个语句,不会走索引。