SQL 优化索引的作用?
字符串大小比较的规则?
通过一定将数据按一定规则排序(按照数据大小排序),一次IO操作尽可能缩小数据范围,避免全表扫描,索引只能用于查找key是否存在(相等)
1
mysql为例 负向查询不能使用索引 select name from user where id not in (1,3,4); 应该修改为: select name from user where id in (2,5,6); 原因:索引只能用于查找key是否存在(相等)2
前导模糊查询不能使用索引 如:select name from user where name like ‘%zhangsan’
非前导则可以:
select name from user where name like ‘zhangsan%’
建议可以考虑使用 Lucene 等全文索引工具来代替频繁的模糊查询。
原因:字符串也可以比较大小的
原来对于数字与非数字混合的字符串,在进行大小比较的时候,如果两字符串长度相等,那么两字符串就会比较相同位置的字符,比较时若字符是数字,则直接比较,若字符是非数字那么会转换为ascii码进行比较,若在某位置上已经有大小之分,那么就不会再进行比较。
3
数据区分不明显的不建议创建索引 如 user 表中的性别字段,可以明显区分的才建议创建索引,如身份证等字段。 字段的默认值不要为 null 这样会带来和预期不一致的查询结果。 在字段上进行计算不能命中索引select name from user where FROM_UNIXTIME(create_time) < CURDATE();
应该修改为:
select name from user where create_time < FROM_UNIXTIME(CURDATE());
最左前缀问题:
如果给 user 表中的 username pwd 字段创建了复合索引那么使用以下SQL 都是可以命中索引:
- select username from user where username=‘zhangsan’ and pwd =‘axsedf1sd’
- select username from user where pwd =‘axsedf1sd’ and username=‘zhangsan’
- select username from user where username=‘zhangsan’