我有两个表a,b,他们中的字断都含有一个类型相同的id字段,不用in等集合语句实现查找在字段id包含在a中而不在b中的记录,如果用not in语句可以这样实现:
select a.id from a where a.id not in(select distinct b.id from b)
因为用in语句效率较低,有没有更好的办法实现上面语句达到的功能?

解决方案 »

  1.   

    select distinct a.id from tabA as a 
    left join tabB as b on a.id = b.id
    where b.id is null
      

  2.   


    create table A(id int)
    insert A select 1
    union all select 2
    union all select 3
    union all select 4
    union all select 5create table B(id int)
    insert B select 2
    union all select 3select A.id from A 
    where not exists(select * from B where id=A.id)--result
    id          
    ----------- 
    1
    4
    5(3 row(s) affected)
      

  3.   

    to:marco08(天道酬勤) 
    你用到的是集合函数,实质上和用in的效率是一样的。
    to:hellowork(一两清风)
    你的方法理论上是可以的,但外连接的效率也好像不怎么高,估计会比集合函数好一些不知道还有没有其它的解决办法?望各位赐教
      

  4.   

    select A.id from A 
    where not exists(select * from B where id=A.id)
      

  5.   

    to:marco08(天道酬勤) 
    你用到的是集合函数,实质上和用in的效率是一样的。---------
    有用到集合函数马?我顶他的...使用not exists 比not in 快
      

  6.   

    use test
    go
    declare @a table (a int)
    declare @b table (b int)
    insert @a values(1)
    insert @a values(2)
    insert @a values(3)
    insert @a values(4)
    insert @a values(5)
    insert @b values(1)
    insert @b values(2)
    insert @b values(3)
    select a.a from @a a left outer join @b b on a.a=b.b
    where b.b is null
    a           
    ----------- 
    4
    5(所影响的行数为 2 行)
      

  7.   

    我写了一个语句,好像也比较的快:
    select distinct id from a
    minus
    select distinct id from b
      

  8.   

    ------------
    select distinct id from a
    minus
    select distinct id from b
    ------------学习中.....
    这个好像....
    不好说.