当前位置:编程学堂 > sql优化的几种方法

sql优化的几种方法

  • 发布:2023-10-01 19:00

select id from t where num=10 union all select id from t where num=20

登录后复制

www.sychzs.cn 和 not in 也要慎用,否则会导致全表扫描,如:

select id from t where num in(1,2,3)
登录后复制

对于连续的数值,能用 between 就不要用 in 了:

select id from t where num between 1 and 3
登录后复制

6.下面的查询也将导致全表扫描:

select id from t where name like '%abc%'
登录后复制

7.应尽量避免在 where 子句中对字段进行表达式操作,这将导致引擎放弃使用索引而进行全表扫描。如:

select id from t where num/2=100
登录后复制

应改为:

select id from t where num=100*2
登录后复制

8.应尽量避免在where子句中对字段进行函数操作,这将导致引擎放弃使用索引而进行全表扫描。如:

select id from t where substring(name,1,3)='abc'--name以abc开头的id
登录后复制

应改为:

select id from t where name like 'abc%'
登录后复制

9.不要在 where 子句中的“=”左边进行函数、算术运算或其他表达式运算,否则系统将可能无法正确使用索引。

10.在使用索引字段作为条件时,如果该索引是复合索引,那么必须使用到该索引中的第一个字段作为条件时才能保证系统使用该索引,

否则该索引将不会被使用,并且应尽可能的让字段顺序与索引顺序相一致。

11.不要写一些没有意义的查询,如需要生成一个空表结构:

select col1,col2 into #t from t where 1=0
登录后复制

这类代码不会返回任何结果集,但是会消耗系统资源的,应改成这样:

create table #t(...)
登录后复制

以上就是sql优化的几种方法的详细内容,更多请关注其它相关文章!

相关文章

最新资讯