1:查询模糊匹配
尽量避免在复杂查询中使用 like “%parml%”,因为%会导致相关列索引无法使用。
2:索引问题
不要在建立索引的数据列中进行如下操作:避免对索引字段进行计算操作;避免在索引字段上使用not,<>,! ;避免在索引列上使用IS NULL和IS NOT NULL;避免在索引列上出现函数类型转换;避免在索引列中使用空值;
3:where语法法则
避免在where子句中使用in、not in、or或者having;
3-1可以使用exist和not exist 代替in和not in ;可以使用表链代替exist,having可以用where代替,如果不可以,则可以
select * from orders where customert_name not in (select customert_name from customer)
优化:select * from orders where customert_name not exist (select customert_name from customer)
3-2不要以字符格式声明数字,要以数字格式声明字符(日期同样),否则会引起索引无效,产生表扫描
SELECT emp.ename, emp.job FROM emp WHERE emp.empno = 7369;
--不要使用:SELECT emp.ename, emp.job FROM emp WHERE emp.empno = '7369'
4.应尽量避免在 where 子句中使用!=或<>操作符,否则将引擎放弃使用索引而进行全表扫描。
5.应尽量避免在 where 子句中使用 or 来连接条件,否则将导致引擎放弃使用索引而进行全表扫描,如:
select id from t where num=10 or num=20
可以这样查询:
select id from t where num=10
union all
6.应尽量避免在where子句中对字段进行函数操作,这将导致引擎放弃使用索引而进行全表扫描。如:
select id from t where substring(name,1,3)='abc'--name以abc开头的id
应改为:
select id from t where name like 'abc%'
select id from t where num=20
7 in 和 not in 也要慎用,否则会导致全表扫描,如:
select id from t where num in(1,2,3)
对于连续的数值,能用 between 就不要用 in 了:
select id from t where num between 1 and 3
8 很多时候用 exists 代替 in 是一个好的选择:
select num from a where num in(select num from b)
用下面的语句替换:
select num from a where exists(select 1 from b where num=a.num)
9 索引并不是越多越好,索引固然可以提高相应的 select 的效率,但同时也降低了 insert 及 update 的效率,
因为 insert 或 update 时有可能会重建索引,所以怎样建索引需要慎重考虑,视具体情况而定。
一个表的索引数最好不要超过6个,若太多则应考虑一些不常使用到的列上建的索引是否有必要。
10 尽可能的使用 varchar 代替 char ,因为首先变长字段存储空间小,可以节省存储空间,