SQL从2个表中加入Null值

时间:2018-01-25 12:10:00

标签: sql sql-server

我有2个表,想要将结果从它们中拉回来。 现在名称字段是一个唯一的ID,附有多个数据,即日期和时间。我已经将数据简化到了这里,但这是一般的要点。

表1

Name    Date
John    12th
John    13th
John    15th
John    17th

表2

Name    Colour
John    Red
John    Blue
John    Orange
John    Green

需要的结果

Name    Date    Time
John    12th    NULL
John    13th    NULL
John    15th    NULL
John    17th    NULL
John    NULL    Red
John    NULL    Blue
John    NULL    Orange
John    NULL    Green

我目前正在执行左连接以提取数据但是它会将结果张贴在彼此旁边,如

John 12th Red

1 个答案:

答案 0 :(得分:4)

您想要union all

select name, date, null as colour
from t1
union all
select name, null, colour
from t2;

我冒昧地命名第二列colour而不是time,只是因为这在问题的背景下更有意义。