gpt4 book ai didi

sql - 如何合并/更新 2 个相同的 SQL 表

转载 作者:行者123 更新时间:2023-12-04 23:18:25 26 4
gpt4 key购买 nike

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

原始表 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

最佳答案

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

关于sql - 如何合并/更新 2 个相同的 SQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30222366/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com