1. 负向查询不能使用索引
例如:
elect * from order where status!=0 and stauts!=1;
select name from order where status not in (0,1);
可优化为: 用in查询:
select * from order where status in(2,3)
2. 前导模糊查询不能使用索引
例如:
select name from user where name like '%xxx';
可优化为: 使用非前导就可以使用索引
select name from user where name like 'xxx%';
ps:MyISAM 存储引擎也可以做全文检索,不过只支持英文,相信现在应该也没人使用它了。建议使用
solr
、es
等第三方开始工具实现全文检索功能。
3. 数据区分不明显的不建议创建索引
例如: user 表中的性别字段,可以明显区分的才建议创建索引,如身份证等字段。
select * from user where sex=1
原因:性别只有男,女,每次过滤掉的数据很少,不宜使用索引。过度索引,影响更新速度,必须在唯一性较高的字段上建立非聚集索引
经验上,能过滤80%数据时就可以使用索引。对于订单状态,如果状态值很少,不宜使用索引,如果状态值很多,能够过滤大量数据,则应该建立索引
4.字段的默认值不要为 null
在创建表的时候如果在业务中能保证非null的字段,建议明确标示not null 因为mysql中对null需要特殊的标示。使用not null 字段更节省空间。对接下来的索引构建也有好处
5. 如果明确知道只有一条记录返回
select name from user where username='xxxx' limit 1
提高效率,可以让数据库停止游标移动,停止全表扫描。