sql中有些比较符号和算式的运用,会导致索引无法起到应有的作用,需要额外注意
- 使用负向条件查询,导致索引失效。
例如 :not in ,!= , <> 这些
select from order where status!=0 and stauts!=1
not in/not exists都不是好习惯
可以优化为in查询:
select from order where status in(2,3)
2. 使用模糊查询,前导模糊查询不能是索引生效,而后置模糊查询可以。
例如 :select from order where desc like '%XX' -- 不能生效
3. 数据区分度不大的字段 不宜使用索引。
例如 :select from user where sex=1
4. 运算式中的字段无法使用其上的索引,或者说在属性上进行计算无法命中其索引。
例如 :select from order where YEAR(date) < = '2017' 可优化为 elect from order where date < = '2017-01-01 。
5. 存在null值的列,如果建立索引,查询会存在隐患。
单列索引不存 null 值,复合索引不存全为 null 的值,这样救护导致 查询数据时,无法体现出这null值的数据。
6. 复合索引最左前缀原则。
我们知道数据库索引 采用的是B+树结构,而B+树的遍历原则,一般是从左遍历的,如果最左边的元素都无法遍历到,那么就无法界定范围,从而进一步查找下去,例如 对 name,age,id 三个列分别建立了索引 index_a,index_b,index_c ,那么 要想使复合索引生效,index_a必须使用到,并且放在where后的第一个条件。
7. 把计算放到业务层而不是数据库层,除了节省数据的CPU,还有意想不到的查询缓存优化效果
select from order where date < = CURDATE()
这不是一个好的SQL实践,应该优化为:
$curDate = date('Y-m-d'); $res = mysqlquery( 'select from order where date < = $curDate');
原因:释放了数据库的CPU 多次调用,传入的SQL相同,才可以利用查询缓存