2015-05-13 118 views
4

我有2个具有相同结构的SQL表格。一个是第二个的更新版本。我如何合并2,以便新表的记录优先于另一个,并且新表中没有更新的记录仍然包含在内?如何合并/更新2个相同的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 

结果欲

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

感谢, MC

回答

5

​​3210将返回第一个非空值。结合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

尝试联合:

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作为列名。非常糟糕的主意。