前提
  A表:
    ID     Name
   001     John
   002     Mary  B表:
    ID     Name
   002     Smith
   003     Jim
问题:
   返回下面要求的结果集:
   1,以A表为主,并以ID作为比较条件,当A与B表中的ID重复时,
      显示A表中的记录。
   2,A与B表中的ID不重复的记录全都显示。
结果集:
    ID     Name
   001     John    --A表
   002     Mary    --A表
   003     Jim     --B表
   PS:想用UNION做交集,但A和B表中的002都被显示出来了。
    请问大家怎么做呢?

解决方案 »

  1.   

    --> 测试数据:#a
    if object_id('tempdb.dbo.#a') is not null drop table #a
    create table #a(ID varchar(8), Name varchar(8))
    insert into #a
    select '001', 'John' union all
    select '002', 'Mary'
    --> 测试数据:#b
    if object_id('tempdb.dbo.#b') is not null drop table #b
    create table #b(ID varchar(8), Name varchar(8))
    insert into #b
    select '002', 'Smith' union all
    select '003', 'Jim'select isnull(a.ID,b.ID)ID, isnull(a.Name,b.Name)Name
    from #a a full join #b b on a.ID=b.ID/*
    ID       Name
    -------- --------
    001      John
    002      Mary
    003      Jim
    */
      

  2.   

    --> 测试数据:#a
    if object_id('tempdb.dbo.#a') is not null drop table #a
    create table #a(ID varchar(8), Name varchar(8))
    insert into #a
    select '001', 'John' union all
    select '002', 'Mary'
    --> 测试数据:#b
    if object_id('tempdb.dbo.#b') is not null drop table #b
    create table #b(ID varchar(8), Name varchar(8))
    insert into #b
    select '002', 'Smith' union all
    select '003', 'Jim'
    select * from #a
    union all
    select * from #b where not exists(select 1 from #a where #a.ID=#b.ID)
    /*
    ID Name
    001 John
    002 Mary
    003 Jim
    */
      

  3.   


    select * from A
    union all
    select * from B a where not  exists(selecr 1 from A where id=a.id)