简体   繁体   中英

sql merge two tables in which the common fields are not complete

In SQL server 2008, I have the following two tables

  Table_1:
C1  C2
A   TypeStringA-1
B   TypeStringA-2
C   TypeStringA-3
D   TypeStringA-4
E   TypeStringA-5

  Table_2
C1  C2
A   TypeStringB-1
B   TypeStringB-2
D   TypeStringB-3
E   TypeStringB-4

And I want to show the following data:

  Result
A  TypeStringA-1 TypeStringB-1
B  TypeStringA-2 TypeStringB-2
C  TypeStringA-3 Null
D  TypeStringA-4 TypeStringB-3
E  TypeStringA-5 TypeStringB-4

Right now what I have is two sub-queries and a where:

select
query1.C1
query1.C2
query2.C2
(select C1, C2 
from Table_1) as query1
(select C2
from table_2) as query2
where query1.C1 = query2.C1
order by query1.C1

However logically in my result I am not having the Null data that I need to show, this is what I am getting:

  Result
A  TypeStringA-1 TypeStringB-1
B  TypeStringA-2 TypeStringB-2
D  TypeStringA-4 TypeStringB-3
E  TypeStringA-5 TypeStringB-4

The question is what should I use to shot the table as I want with a Null data?.

select  coalesce(t1.C1, t2.C1)
,       t1.C2
,       t2.C2
from    Table_1 t1
full outer join
        Table2 t2
on      t1.C1 = t2.C1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM