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

求助:一个sql的写法,可能是很常见的,但是不知道如何修改
我有个需求是这样的:
A B两个表
A和B是一对多外键关系
A的主键是aid同时也是B的外键,B的主键是bid
我现在要取A表中没有在B表出现

我的 sql是:
第一种
select a.aid
from A a
where a.aid not in (select aid from B)

这个因为A B表数量大,太慢。

第二种
select a.aid
from A a,B b
where A.aid=B.aid(+)
  and B.bid is null

这个好像倒是挺快的,但是我不确定对不。

第三种
select a.aid
from A a
where a.aid not in (select aid from B where aid=a.aid)

高手指点下。数据量比较大。不知道该怎么写才好呀。
第二种不确定是不是正确呀。查的结果是一样的。


------解决方案--------------------
select a.aid 
from A a 
where not exists
(select 'x' from b
where a.aid = b.aid )
------解决方案--------------------
2是有这种写法的,我认为是对的,说了可能出错的原因了,
你这用是没问题的

2效率最高
------解决方案--------------------
第二种是对的哦,多表连接的里的左连接的嘛,没错撒
------解决方案--------------------
实现的方法很多,个人建议用not exists,在数据很多的时候还是比较快的,not in 的话是比较慢的
------解决方案--------------------
select sid from B
minus 
select sid from A

得到a中没有的sid
------解决方案--------------------
第二种方法是对的。
左外连接如果不匹配的话,ORACLE会自动赋一个null值。
所以当b.bid=null就找出了在A表而B表中没有的。