【转】SQL语句优化技巧

2017-06-20  本文已影响25人  王帅199207
select id from t where num is null

可以在num上设置默认值0,确保表中num列没有null值,然后这样查询:

select id from t where num=0
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
select id from t where name like ‘�c%’

若要提高效率,可以考虑全文检索。

select id from t where num in(1,2,3)

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

select id from t where num between 1 and 3
select id from t where num=@num

可以改为强制查询使用索引:

select id from t with(index(索引名)) where num=@num
select id from t where num/2=100

应改为:

select id from t where num=100*2
select id from t where substring(name,1,3)=’abc’–name以abc开头的id
select id from t where datediff(day,createdate,’2005-11-30′)=0–’2005-11-30′生成的id

应改为:

select id from t where name like ‘abc%’
select id from t where createdate>=’2005-11-30′ and createdate<’2005-12-1′
select col1,col2 into #t from t where 1=0

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

create table #t(…)
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)

连原作者都有可能看糊涂的SQL语句,数据库也一样会看糊涂。学会这些技巧,就不必在写完代码很久以后拿着2页长的SQL语句自己也看不懂了。

上一篇 下一篇

猜你喜欢

热点阅读