sql优化的几种方法
- 查询的时候避免全表扫描,在经常会where和order by的列上建立索引
- 尽量避免在where里对字段进行null值判断,否则的话会让数据库引擎放弃索引而进行全表扫描,如
select id from students where num is null
-- 尽量避免(num is null)这种的查询可以在num列上设置默认值0,确保num列上没有null值,然后可以这样查询
select id from students where num=0
- 避免在where语句里使用!=,<,>等操作符,否则的话会让数据库引擎放弃索引而进行全表扫描
- 避免在where语句里使用or来链接条件,否则的话会让数据库引擎放弃索引而进行全表扫描,例如
select id from t where num=10 or num=20 -- 上面的这种不可取 select id from t where num=10 union all select id from t where num=20 -- 最好使用这一种
- in 和not in 也要慎用,否则会导致全表扫描,如
select id from students where num in(1,2,3) -- 对于连续的数值,能用 between 就不要用 in 了: select id from students where num between 1 and 3
- 使用通配符的时候,不要在前面加%,否则的话会不走索引直接全表扫描,如
select id from t where name like '%abc%'
- 避免在where语句中对字段进行表达式操作,否则的话会不走索引直接全表扫描。还有不要在where语句的=左边做函数、算数运算、表达式运算,,否则的话会不走索引直接全表扫描。如
select id from t where num/2=100 -- 应改为: select id from t where num=100*2
- 在使用索引字段作为条件时,如果该索引是符合索引,那么必须使用到该索引的第一个字段作为条件时才能保证系统使用该索引,否则该索引将不会被使用,并且应该尽可能的让字段顺序与索引顺序一致。
- 不要使用select * from t, 应该用具体的字段代替*,用到什么字段就查什么字段
- 很多时候用 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)