【问题标题】:Consume The Changes / Deltas using Postgresql使用 Postgresql 使用更改/增量
【发布时间】:2016-10-12 19:53:08
【问题描述】:

以下是我的场景:

我有 2 个登陆表 source_table 和 destination_table。

我需要一个查询/查询,它将使用新行以及源表中的更新行更新目标表。

样本数据为:

source table:
id    name    salary
1     P1      10000
2     P2      20000

target table:
id    name    salary
1     P1      8000

预期的输出应该是:

target table:
id    name    salary
1     P1      10000 (salary updated)
2     P2      20000 (new row inserted)

这似乎不起作用:

select * from user_source 
except 
select * from user_target as s

INSERT INTO user_target (id, name, salary) 
VALUES (s.id, s.name, s.salary) WHERE id !=s.id

UPDATE user_target 
  SET name=s.name, salary=s.salary,
WHERE id = s.id

【问题讨论】:

  • @a_horse_with_no_name 完成!

标签: postgresql upsert


【解决方案1】:

对我来说似乎是一个简单的insert ... on conflict

insert into target_table (id, name, salary)
select id, name, salary 
from source_table
on conflict (id) do update 
  set name = excluded.name, 
      salary = excluded.salary;

这假定id 列是主键(或唯一键)。查看样本数据(id, name) 也可能是独一无二的。在这种情况下,您需要更改 on conflict() 子句,并且显然也要删除 name 列的更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多