我有个需求是这样的:
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)高手指点下。数据量比较大。不知道该怎么写才好呀。
第二种不确定是不是正确呀。查的结果是一样的。
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)高手指点下。数据量比较大。不知道该怎么写才好呀。
第二种不确定是不是正确呀。查的结果是一样的。
from A a
where not exists
(select 'x' from b
where a.aid = b.aid )
select count(*) from b where bid is null //记录是0就是对的你这个是主件不会是null
我跑了几次总数都是一致的。
很郁闷呀。第二种写法是我自己乱写的,但是我想左联之后B表没有的数据就是B的id为空了。
minus
select sid from A得到a中没有的sid
左外连接如果不匹配的话,ORACLE会自动赋一个null值。
所以当b.bid=null就找出了在A表而B表中没有的。