表中字段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上用到了索引,总的开销也很小,但是效率明显差别,这是为什么呢?
select * from table where A in (select code from dictonary)即使同样有1000个code,速度还是飞快。
观察这2个语句的执行计划,都差不多,A上用到了索引,总的开销也很小,但是效率明显差别,这是为什么呢?
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唯一
select * from table where A='11' or A='22' or....
你再执行几次看看,后面几次是不是会快?