合并两个表,将值从一个继承到另一个

时间:2012-05-16 16:05:15

标签: sql-server-2008 tsql union

我希望使用UNION或其他技术将两个表格显示为单个结果。

ID字段与两个表相关。

第二个表缺少一个字段,因此应该从第一个表中假设缺失值。

下面的示例代码可以使用,但对于大型数据集来说非常慢。

有没有更有效的解决方案?

T1:                       T2:
+----+-------+--------+   +----+------+
| id | name  | town   |   | id | name |
+----+-------+--------+   +----+------+
|  1 | Alice | London |   |  1 | Bob  |
|  2 | Alan  | Zurich |   +----+------+
+----+-------+--------+   

期望的结果:

+----+-------+--------+
| id | name  | town   |
+----+-------+--------+
|  1 | Alice | London |
|  2 | Alan  | Zurich |
|  1 | Bob   | London |
+----+-------+--------+   

示例代码:

with T1 as
(
    select * from 
    (
        values
            (1,'Alice','London') ,
            (2,'Alan','Zurich') 
    ) as t (id,name,town)
), T2 as
(
    select * from 
    (
        values
            (1,'Bob') 
    ) as t (id,name)
), T2WithTown as
(
    select t2.id,t2.name,t1.town from T2
    inner join T1 on t2.id=t1.id
)

select id,name,town from T1
union
select id,name,town from T2WithTown

3 个答案:

答案 0 :(得分:0)

就像这样:

with T1 as
(
    select * from 
    (
        values
            (1,'Alice','London') ,
            (2,'Alan','Zurich') 
    ) as t (id,name,town)
), T2 as
(
    select * from 
    (
        values
            (1,'Bob') 
    ) as t (id,name)
), T2WithTown as
(
    select t2.id,t2.name,t1.town from T2
    inner join T1 on t2.id=t1.id
)

select id,name,town from T1
union
select T2.id, T2.name, T1.town
from T1
inner join T2 on T2.id = T1.id

答案 1 :(得分:0)

示例数据显示两个表都有不同的值。所以我更喜欢UNION ALL

Select ID, Name, Town From T1
UNION ALL
select T2.ID, T2.Name, T1.Town
from T1
INNER JOIN T2 on T2.id = T1.id

答案 2 :(得分:0)

select id,name, town from t1
union 
select id,name, (select top 1 town from t1 where t1.id=t2.id) from t2