table_aclass_id    xuesheng_id
1               1
1               2
1               3
2               1
2               2
2               3
table_bclass_id    xuesheng_id
1                1
2                3有两个表 
A表包含B表 (也就是说A表里既有B表的数据也有其他数据)
我想查询 A表里不包含B表的的值
就是 反交集 ,还有class_id和xuesheng_id全部是主键
请大哥们帮忙

解决方案 »

  1.   

    declare @a table (class_id int, xuesheng_id int)
    insert @a
    select 1, 1 union all
    select 1, 2 union all
    select 1, 3 union all
    select 2, 1 union all
    select 2, 2 union all
    select 2, 3declare @b table (class_id int, xuesheng_id int)
    insert @b
    select 1, 1 union all
    select 2, 3--方法1
    select class_id, xuesheng_id from
    (select a.*, b_class_id = b.class_id from @a a left join @b b on a.class_id = b.class_id and a.xuesheng_id = b.xuesheng_id) c
    where b_class_id is null--方法2
    select * from @a where class_id * power(10, len(xuesheng_id)) + xuesheng_id not in (select class_id * power(10, len(xuesheng_id)) + xuesheng_id from @b)--方法3
    select * from @a where cast(class_id as varchar) + cast(xuesheng_id as varchar) not in (select cast(class_id as varchar) + cast(xuesheng_id as varchar) from @b)/*
    哪个方法效率高,你自己测试一下了。期待其它更优良的方法。
    */
      

  2.   

    ---试试这个语句的效率?
    Select * From @a A Where Not Exists
            (Select 1 From @b Where class_id=A.class_id And xuesheng_id=A.xuesheng_id)
      

  3.   

    SoftwKLC(自由的飞鸟)
    用exists的效率最高
    顶一个