1.避免在 where 的子句中使用!= 或者 <> 操作符,否则引擎将放弃使用索引而进行全表扫描
2.避免在 where 的子句中使用 or 来连接条件,否则引擎将放弃使用索引而进行全表扫描 。
例如: select number from a where uid = 1 or uid = 2
优化后 : select number from a where uid = 1 union all select number from a where uid = 2
union和union all的区别是,union会自动压缩多个结果集合中的重复结果,而union all则将所有的结果全部显示出来,不管是不是重复。 Union:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序; Union All:对两个结果集进行并集操作,包括重复行,不进行排序;
Union因为要进行重复值扫描,所以效率低。如果合并没有刻意要删除重复行,那么就使用Union Al
3.避免模糊查询中的两个%
例如: select number from a where name like '%lbz%' (加入双%也会导致全盘扫描)
4.避免在 where 字句中对字段进行表达式操作
例如 : select number from a where id / 2 = 100
优化后 : select number from a where id = 100*2
5.避免在 where 的子语句中对字段进行函数操作,否则会导致引擎放弃索引而开始对全表进行扫描
例如 : select uid from a where subString(name,1,3) = 'lbz'
优化后 : select uid from a where name like 'lbz%'
6.避免在 where 的子语句中 等号的左边进行 函数、表达式、算数运算 或者其他表达式运算,否则引擎都将会放弃索引从而进行全表的扫描,无法正常使用索引
7.对查询SQL进行优化,应避免对全表进行扫描,首先应考虑在 where 及 order by 涉及的列上建立索引
8.禁止使用 select * from a ,应该用具体的字段列表代替 " * " ,一定要加上属性列名
9.大部分情况用 exists 代替 in
例如 :select number from a where id in (select id from b)
优化后 : selecr number from a exists (select id from b where id = a .id )
10.并不是所有的索引对查询都有效果,SQL是根据表中数据来进行查询优化的,当索引列有大量的数据重复时,SQL查询可能不会去利用索引,并不是所有的索引对查询都有效,SQL是根据表中的数据来进行查询优化的,当索引列有大量的数据重复时,SQL查询可能不会去利用索引