table1:
no     name       city
4      zhang      bj
6      li         nj
12     zhao       dbtable2:
no     job          name
1      PG           qian
4      PL           sun
8      PM           wu
10     SE           wang查询结果如下
no     name       city   job
1      qian              PG
4      sun        bj     PL
6      li         nj
8      wu                PM           
10     wang              SE
12     zhao        db即查询两个表中的所有字段,当no相同时用table2中的name替换table1中的name。 

解决方案 »

  1.   

    select tb.no,tb2.name,city,job
    from tb join tb2 on tb.no=tb2.nounion select no,name,city,''
    from tb t 
    where not exists(select 1 from tb2 where t.no=tb2.no)union 
    select no,name,'',job
    from tb2 s
    where not exists(select 1 from tb where s.no=tb.no)
      

  2.   

    select isnull(a.no,b.no) as no,isnull(a.name,b,name) as name,a.city,b.job
    from tb1 full join tb2 on a.no=b.no
      

  3.   

    select tb.no,tb2.name,city,job
    from tb join tb2 on tb.no=tb2.nounion select no,name,city,''
    from tb t 
    where not exists(select 1 from tb2 where t.no=tb2.no)union 
    select no,name,'',job
    from tb2 s
    where not exists(select 1 from tb where s.no=tb.no)
      

  4.   

    select
     isnull(a.no,b.no)no,
     isnull(a.name,b,name)name,
     a.city,b.job
    from
     tb1 full join tb2 on a.no=b.no
      

  5.   

    no          name city job
    ----------- ---- ---- ----
    1           qian NULL PG
    4           sun  bj   PL
    6           li   nj   NULL
    8           wu   NULL PM
    10          wang NULL SE
    12          zhao db   NULL(6 row(s) affected)
      

  6.   

    select
     isnull(a.no,b.no)no,
     isnull(a.name,b,name)name,
     a.city,b.job
    from
     tb1 full join tb2 on a.no=b.no