【问题标题】:Combining two tables and updating cells where IDs match [duplicate]组合两个表格并更新 ID 匹配的单元格 [重复]
【发布时间】:2021-02-24 17:14:10
【问题描述】:

我有两张表,其中包含我希望合并的客户数据。一张是 2013-2017 年的旧数据,一张是 2018 年至今的数据。

我基本上想使用 UNION 将旧数据粘贴在新数据下,这很简单。但是,我有两个表中都存在的老客户(可以在 customer_id 上加入)。

理想情况下,我编写的查询将执行以下操作:

如果 customer_id 存在于新数据中,它只会将 newtable.starting_date 更新为 oldtable.starting_date。

如果新数据中不存在 customer_id,则将整行添加到表中。

我在 MySQL 中这样做。

【问题讨论】:

  • INSERT .. ON DUPLICATE KEY UPDATE
  • 参见INSERT下的手册

标签: mysql sql duplicates sql-update sql-insert


【解决方案1】:

你想要insert ... on duplicate key吗?

为此,您需要目标表中 customer_id 列上的唯一键或主键。

假设两个表都有三列(customer_idstarting_dateending_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)

【讨论】:

    【解决方案2】:

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      • 2016-08-25
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      相关资源
      最近更新 更多