1.最左前缀匹配原则。
mysql会一直向右匹配直到遇到范围查询(>、<、between、like)就停止匹配。所以要尽量把“=”条件放在前面,把这些条件放在最后。
不会用到b的索引:
where a=1 and c>0 and b=2
会用到b的索引:
where a=1 and b=2 and c>0
2.尽量选择区分度高的列作为索引,区分度的公式是count(distinct col)/count(*),表示字段不重复的比例,比例越大我们扫描的记录数越少。
3.当取出的数据超过全表数据的20%时,不会使用索引。
4.使用like时注意:
不使用索引:
like ‘%L%’
使用索引:
like ‘L%’
5.尽量将or 转换为 union all
不使用索引:
select * from user where name=’a’ or age=’20’
使用索引:
select * from user where name=’a’ union all select * from user where age=’20’
6.字段加函数不会使用索引。所以尽量把函数放在数值上
不使用索引:
where truncate(price) = 1
使用索引:
where price > 1 and price < 2
