日期:2014-05-17  浏览次数:21053 次

用or查询时条件多会严重影响性能?
表中字段A上加了索引,查找时使用如下语句(由程序拼出的条件)

select * from table where A='11' or A='22' or....

总共有1000个or,查询非常慢,耗时几分钟。

而如果写成类似
select * from table where A in (select code from dictonary)

即使同样有1000个code,速度还是飞快。


观察这2个语句的执行计划,都差不多,A上用到了索引,总的开销也很小,但是效率明显差别,这是为什么呢?


------最佳解决方案--------------------
估计你是sql语句解析花的时间多吧。
select * from table where A='11' or A='22' or....
你再执行几次看看,后面几次是不是会快?
------其他解决方案--------------------

select * from table where A in (select code from dictonary)
--需要扫描2张表

select * from table where A='11' or A='22' or....
--只需要扫描1张表,

如果dictonary表很大,那么这种差别会更加明显。 至于楼主说的速度飞快。 建议楼主把完整的例子贴出来,并且给出具体的执行计划和执行时间。 要用数据说话。 





------其他解决方案--------------------
同意楼上的观点。飞快的概念不好理解啊。贴出完整的执行计划
------其他解决方案--------------------

--如果dictonary数据量不大
select * from table where A in (select code from dictonary);
--如果dictonary数据量很大
select * from table where exists (select 1 from dictonary where A = code);
/*或者*/
select t.* from table t,dictonary d
where t.A = d.code;  --要求dictonary的code唯一

------其他解决方案--------------------
确实是用在sql解析上了,再次执行这1000个or只需要0.1秒。