简体   繁体   中英

SQL Server query about joining 2 table with union

I have two tables T1 and T2 , both of them contain a column ID and value .

I need to join T1 and T2 into T3 by means of ID .

T3 should contain columns ID , T1Value , and T2Value .

The main requirement is, ID of T1 and T2 is possible not mapped

T1 :

ID   VALUE
-----------
1    hi
2    hello

T2 :

ID   VALUE
----------
2    kitty
3    dog

Then, T3 should be

ID   T1VALUE   T2VALUE
----------------------
 1   hi
 2   hello     kitty
 3             dog

Is it possible to achieve this without using pivot table, or temp table (ideally should be a single executable query)?

Thanks.

You can use FULL OUTER JOIN

SELECT ID      = COALESCE(T1.ID, T2.ID),
       T1VALUE = T1.VALUE,
       T2VALUE = T2.VALUE
FROM   T1
       FULL OUTER JOIN T2
       ON  T1.ID = T2.ID

There are lots of example on FULL OUTER JOIN . just search for it

Another way is to use UNION ALL

SELECT T1.ID, T1VALUE = T1.VALUE, T2VALUE = NULL
FROM   T1

UNION ALL

SELECT T2.ID, T1VALUE = NULL,     T2VALUE = T2.VALUE
FROM   T2

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