sql中not in 、minus 、not exists效率问题

例子:
create table A (
num number(10));
create table B (
num number(10));

表A中记录为1 2 3 9
表B中记录为2 3 4 5

现在要查询出1 9,可以用下面三个语句
(1)select a.num from A a where a.num not in (select b.num from B b);
(2)select a.num from A a minus select b.num from B b (这里a.num和b.num前不需要加distinct也会自动列出不重复的数据,要求两个查询出的列数相同,字段类型相同)
(3)select a.num from A a where not exists (select b.num from B b where b.num=a.num)

当前表A、B的数据量很小以上三个sql查询效率上是不同的,当量大的情况下(1)和(2)(3)效率差距较大,
本人只使用时的数据量(A表4800条记录,B表11600条记录),执行时间如下
(1)  139S
(2)   3S
(3)  2.4S
均是初始执行时间

后期再研究为什么效率会如此大的差距

补充一(转自 ITPUB论坛):
minus   剔重且会排序
not exists/not in所谓的anti join,当然前者是真正的anti join,not in可能遇到null麻烦点,可能性能低,如果解决了null的问题,not exists/not in基本差别很小了,cbo会转为等价的写法。他们会返回所有满足条件的主表数据,不管是否有重复。

如果主表不存在重复数据,minus和not exists结果是可以相互转为等价的,但是因为有排序,性能可能要差点,当然排序是一般情况下有,如果全部能从索引获取什么的,可能会消除。

还有种是外连接写法,也可以转成和anti join等价的结果
select a.* from a,b where a.id=b.id(+) and b.id is null;
有时候not exists,not in什么的走不了anti join,也可以考虑这种写法,join在oracle里高效的算法是比较多的

猜你喜欢

转载自weiljava.iteye.com/blog/1546198