SQL语句优化方式
- 不要使用*号进行查询操作,使用具体字段.
- 索引
- 在where子句和order by 涉及的字段上合理的添加索引.
- where 子句优化
- 避免在where子句中对null值进行判断,应对字段设置默认值
Select id from t where num is null 可以对null值设置默认值为-1(根据自己的实际情况设置) 判断null可以使用 select id from t where num = -1
- 避免在where子句中使用!= 或者<>操作符.
- 尽量避免where子句中使用or 来连接条件
select id from t where num = 1 or num = 5 /*可以优化为*/ select id from t where num = 1 unicon all select id form t where num = 5
- in 和not in 也要慎用
/*连续条件*/ select id from t where num in (1,2,3) /*可以使用 between and */ select id from t where num between 1 and 3 /*更多可以使用exists 代替 in*/ select num from a where num in (select num from t) /*替换语句*/ select num from a where EXISTS (select num from b where a.num = b.num)
- 模糊查询SQL优化
-
/*正常情况下,百分号在后面可以使用索引*/ select nickname from t where nickname like ‘DBA%‘ /*百分号在前面,不能使用索引,解决方案.改写sql,添加reverse索引*/ create index idx_t1_name on t1(reverse(name)) select name from t1 where reverse(name) like reverse(‘
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/SQL/21468.html