我有个需求是这样的:
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)高手指点下。数据量比较大。不知道该怎么写才好呀。
第二种不确定是不是正确呀。查的结果是一样的。

解决方案 »

  1.   

    select a.aid 
    from A a 
    where not exists
         (select 'x' from b
          where  a.aid = b.aid )
      

  2.   

    第二种写法錯誤一般情況下 NOT EXISTS 比NOT IN 的速度要快 (但也不決對)
      

  3.   

    我感觉2是对的,
    select count(*) from b where bid is null    //记录是0就是对的你这个是主件不会是null
      

  4.   

    错在哪里呀?能不能具体说下。
    我跑了几次总数都是一致的。
    很郁闷呀。第二种写法是我自己乱写的,但是我想左联之后B表没有的数据就是B的id为空了。
      

  5.   

    实现的方法很多,个人建议用not exists,在数据很多的时候还是比较快的,not in 的话是比较慢的 
      

  6.   

    select sid from B
    minus 
    select sid from A得到a中没有的sid
      

  7.   

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