如何合并或更新两个相同的SQL表

4

我有两个结构相同的SQL表。其中一个是第二个表的更新版本。我该如何合并这两个表,以便较新的表记录优先于另一个表,并且在较新的表中没有更新的记录仍然包括在内?

原始表ID(是主键):

ID, NAME, ADDRESS
11   AL    1 main street
22   BOB   2 main street
33   CHAZ  3 main street

更新的表格

ID, NAME, ADDRESS
11  AL     99 maple street
22  BOB    2 main street

Result I want

ID, NAME, ADDRESS
11    AL   99 maple street
22    BOB  2 main street
33    CHAZ 3 main street

感谢您,MC。
3个回答

5

coalesce函数将返回第一个非空值。与left join结合使用,它将首先使用新数据,如果为空则使用旧数据。

select coalesce(u.id, o.id) as id,
       coalesce(u.name, o.name) as name,
       coalesce(u.address, o.address) as address
from original_table o
left join updated_table u on u.id = o.id

2
UPDATE o
SET Name=u.Name
    ,Address=u.Address
from [original] o
inner join [updated] u on u.id = o.id

0

Try union:

Select id as uid, name, address from new_table
Union 
Select id, name, address from old_table
Where id not in (select id from new_table)

此外,尽量不要将id用作列名。这是一个非常糟糕的想法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接