我有两个包含客户数据的表,我希望合并这两个表。一个是2013-2017年间非常旧的数据,另一个是2018年-现在的数据。
基本上,我希望使用UNION将旧数据放在新数据下,这非常简单。但是,我有两个表中都存在的老客户(可以在customer_id上联接)。
理想情况下,我编写的查询将执行以下操作:
如果customer_id出现在新数据中,它将只用oldtable.starting_date更新newtable.starting_date。
如果customer_id不存在于新数据中,则会将整行添加到表中。
我正在用MySQL做这件事。
发布于 2020-11-13 01:02:23
你想要insert ... on duplicate key吗
为此,您需要对目标表中的列customer_id使用唯一键或主键。
假设两个表都有三列(customer_id、starting_date、ending_date),则可以将查询表述为:
insert into newtable (customer_id, starting_date, ending_date)
select customer_id, starting_date, ending_date
from oldtable
on duplicate key update starting_date = values(starting_date)发布于 2020-11-13 01:02:41
MySQL不支持完全外部联接。但是你可以这样做:
select coalesce(o.starting_date, n.starting_date) as starting_date,
. . .
from newdata n left join
olddata o
on n.customer_id = o.customer_id
union all
select . . .
from olddata o
where not exists (select 1 from newdata n where n.customer_id = o.customer_id);https://stackoverflow.com/questions/64808322
复制相似问题