ITPub博客

首页 > 应用开发 > IT综合 > not in的优化

not in的优化

原创 IT综合 作者:zgy13121 时间:2009-03-25 09:05:50 0 删除 编辑

使用过oracle的人都知道,not in 不能有效利用索引,所以效率一直是开发人员所担心的。那如何来优化not in呢?(not exists,except 及左关联)

其实在oracle中可以用minus,在db2里用except实现这个需求。 具体实现思路是

1 假设一个sql是 select * from taba a where a.cola not in ( select cola from tabb ) 已在taba与tabb上建立索引。

2 select distinct a.* from taba a, ( select cola from taba minus --在db2中用except替换 select cola from tabb ) b --构造一个不在tabb中的列集合 where a.cola=b.cola

3 minus与except的实现由集合理论支撑,高效。

4 except是标准sql中的,一般都有实现。

5 except牵涉到排序,对大数据集合消耗资源较大,(建议数据超大时慎用,但对于几万条,十几万条应该没问题,我测试过比not in 或not exists效率高)。可改用以下方式实现

select distinct a.*

from a,b

where a.cola=b.cola(+)--左关联 oracle语法 db2用left join tab on conditions

and b.cola is null;

[@more@]

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/11419868/viewspace-1019403/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-09-27

  • 博文量
    58
  • 访问量
    245378