'in'在逻辑上相当于'or' 所以是一样的例:表stuff有200000行,id_no上有非群集索引,请看下面这个SQL: select count(*) from stuff where id_no in('0','1') (23秒) ---- 分析: ---- 语法分析器会将in ('0','1')转化 为id_no ='0' or id_no='1'来执行。我们期望它会根据每个or子句分别查找,再将结果 相加,这样可以利用id_no上的索引;但实际上(根据showplan),它却采用了"OR策略" ,即先取出满足每个or子句的行,存入临时数据库的工作表中,再建立唯一索引以去掉 重复行,最后从这个临时表中计算结果。因此,实际过程没有利用id_no上索引,并且完 成时间还要受tempdb数据库性能的影响。 ---- 实践证明,表的行数越多,工作表的性能就越差,当stuff有620000行时,执行时 间竟达到220秒!还不如将or子句分开: select count(*) from stuff where id_no='0' select count(*) from stuff where id_no='1' ---- 得到两个结果,再作一次加法合算。因为每句都使用了索引,执行时间只有3秒, 在620000行下,时间也只有4秒。或者,用更好的方法,写一个简单的存储过程: create proc count_stuff as declare @a int declare @b int declare @c int declare @d char(10) begin select @a=count(*) from stuff where id_no='0' select @b=count(*) from stuff where id_no='1' end select @c=@a+@b select @d=convert(char(10),@c) print @d ---- 直接算出结果,执行时间同上面一样快! ---- 总结: ---- 可见,所谓优化即where子句利用了索引,不可优化即发生了表扫描或额外开销。---- 1.任何对列的操作都将导致表扫描,它包括数据库函数、计算表达式等等,查询时 要尽可能将操作移至等号右边。 ---- 2.in、or子句常会使用工作表,使索引失效;如果不产生大量重复值,可以考虑把 子句拆开;拆开的子句中应该包含索引。 ---- 3.要善于使用存储过程,它使SQL变得更加灵活和高效。
条件有没有什么规律啊??如果实在不行。可以改写成这样试试。 select distinct * from T1 where ACC='条件1' union all select distinct * from T1 where ACC='条件2' union all select distinct * from T1 where ACC='条件3' union all select distinct * from T1 where ACC='条件4' union all select distinct * from T1 where ACC='条件5 ……………… union all select distinct * from T1 where ACC='条件n'
select count(*) from stuff where id_no in('0','1')
(23秒)
---- 分析:
---- 语法分析器会将in ('0','1')转化
为id_no ='0' or id_no='1'来执行。我们期望它会根据每个or子句分别查找,再将结果
相加,这样可以利用id_no上的索引;但实际上(根据showplan),它却采用了"OR策略"
,即先取出满足每个or子句的行,存入临时数据库的工作表中,再建立唯一索引以去掉
重复行,最后从这个临时表中计算结果。因此,实际过程没有利用id_no上索引,并且完
成时间还要受tempdb数据库性能的影响。
---- 实践证明,表的行数越多,工作表的性能就越差,当stuff有620000行时,执行时
间竟达到220秒!还不如将or子句分开:
select count(*) from stuff where id_no='0'
select count(*) from stuff where id_no='1'
---- 得到两个结果,再作一次加法合算。因为每句都使用了索引,执行时间只有3秒,
在620000行下,时间也只有4秒。或者,用更好的方法,写一个简单的存储过程:
create proc count_stuff as
declare @a int
declare @b int
declare @c int
declare @d char(10)
begin
select @a=count(*) from stuff where id_no='0'
select @b=count(*) from stuff where id_no='1'
end
select @c=@a+@b
select @d=convert(char(10),@c)
print @d
---- 直接算出结果,执行时间同上面一样快!
---- 总结:
---- 可见,所谓优化即where子句利用了索引,不可优化即发生了表扫描或额外开销。---- 1.任何对列的操作都将导致表扫描,它包括数据库函数、计算表达式等等,查询时
要尽可能将操作移至等号右边。
---- 2.in、or子句常会使用工作表,使索引失效;如果不产生大量重复值,可以考虑把
子句拆开;拆开的子句中应该包含索引。
---- 3.要善于使用存储过程,它使SQL变得更加灵活和高效。
select distinct * from T1 where ACC='条件1'
union all
select distinct * from T1 where ACC='条件2'
union all
select distinct * from T1 where ACC='条件3'
union all
select distinct * from T1 where ACC='条件4'
union all
select distinct * from T1 where ACC='条件5
………………
union all
select distinct * from T1 where ACC='条件n'