一、优化方法:
- 避免全表扫描、考虑在where及order by涉及的列上创建索引。
- 尽量避免使用不等操作符,如!=或<>。
- 尽量避免在where子句中对字段进行null值判断。可设置默认值以替代。如where num is null 优化为where num=0。
- 尽量避免使用or来连接条件。or连接的字段需全部为索引,才会真正使用到索引扫描,否则使用全表扫描。
- 慎用in 和not in,会导致全表扫描。
- 尽量避免在where子句中对字段进行表达式操作。如:where num/2=100优化为 where num=100*2。
- 尽量避免在where子句中对字段进行函数操作。
- 使用复合索引时,应遵守最左匹配原则。
- 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)。
- 索引并不是越多越好,索引提高select的效率,同时也降低了插入、更新时的效率,因为其插入更新操作可能会重建索引。
- 尽量使用数字型字段。
- 尽可能使用varchar/nvarchar代替char/nchar。
- 不要使用select *,用字段列表进行代替。