随笔-295  评论-26  文章-1  trackbacks-0
select S_10994_1_SYS_MODELTYPE.nextval,a.typeid,'SYS','Mail_Forward','邮件转发模板','Mail Forward Model' from
bse_organization a where not exists (select orgtypeid from SYS_MODELTYPE b where b.orgtypeid=a.typeid and modelcode ='Mail_Forward')
--

select S_10994_1_SYS_MODELTYPE.nextval,typeid,'SYS','Mail_Forward','邮件转发模板','Mail Forward Model' from
bse_organization where typeid not in (
select orgtypeid from SYS_MODELTYPE where modelcode='Mail_Forward'
)

请注意not in 逻辑上不完全等同于not exists,如果你误用了not in,小心你的程序存在致命的BUG:


请看下面的例子:
create table t1 (c1 number,c2 number);
create table t2 (c1 number,c2 number);

insert into t1 values (1,2);
insert into t1 values (1,3);
insert into t2 values (1,2);
insert into t2 values (1,null);

select * from t1 where c2 not in (select c2 from t2);
no rows found
select * from t1 where not exists (select 1 from t2 where t1.c2=t2.c2);
c1 c2
1 3

正如所看到的,not in 出现了不期望的结果集,存在逻辑错误。如果看一下上述两个select语句的执行计划,也会不同。后者使用了hash_aj。
因此,请尽量不要使用not in(它会调用子查询),而尽量使用not exists(它会调用关联子查询)。如果子查询中返回的任意一条记录含有空值,则查询将不返回任何记录,正如上面例子所示。
除非子查询字段有非空限制,这时可以使用not in ,并且也可以通过提示让它使用hasg_aj或merge_aj连接。



大盘预测 国富论
posted on 2007-10-11 16:51 华梦行 阅读(170) 评论(0)  编辑  收藏 所属分类: Oracle

只有注册用户登录后才能发表评论。


网站导航: