若有A和B两张表,关联字段为ID,A中可能有某ID但B中可能没有,也可能B中有某ID,A中没有该ID,现要实现有相同ID的则连接,没有的则对应显示NULL值,怎么写呢

解决方案 »

  1.   


    Full Join
    Select A.*, B.*
    From A
    Full Join B
    On A.ID = B.ID
      

  2.   

    if object_id('a') is not null
    drop table a
    go
    create table a(id int identity(1001,1),name varchar(50))
    insert into a select 'a'
    union all select 'b'
    union all select 'c'
    union all select 'd'
    union all select 'e'
    go
    select * from a
    go
    if object_id('b') is not null
    drop table b
    go
    create table b(id int ,name varchar(50))
    insert into b select 1003,'a'
    union all select 2003, 'b'
    union all select 2001, 'c'
    union all select 1001, 'd'
    union all select 1005,'e'
    go
    select * from b
    select * from a
    go
    select isnull(a.id,null),b.name from a full join b on a.id = b.id
      

  3.   

    完整联接FULL JOIN若要通过在联接结果中包括不匹配的行保留不匹配信息,请使用完整外部联接。
    提供完整外部联接运算符 FULL OUTER JOIN,不管另一个表是否有匹配的值,此运算符都包括两个表中的所有行。
      

  4.   

    Select A.*, B.*
    From A
    Full Join B
    On A.ID = B.ID