检查是否已插入或更新Postgres查询(通过upsert)

时间:2017-03-08 10:25:08

标签: sql postgresql

我想知道是否有可能弄清楚postgres upsert查询是否导致插入或更新。

像这样的psuedocode:

insert into teammates (id, email, avatar, timezone)
values ($1, $2, $3, $4)
on conflict (id) do update set
  avatar = $3,
  timezone = $4
returning id, (updated = didUpdate);

2 个答案:

答案 0 :(得分:0)

手动检查或执行SELECT后跟UPSERT以下列的方法,然后查看。

  avatar = $3,
  timezone = $4

您还可以拥有一个名为DATETIME的{​​{1}}列,该列应在每次LastModified操作时更新。那么你就可以找到它了。

答案 1 :(得分:0)

有必要进行手动CTE upsert:

with u as (
    update teammates
    set (avatar, timezone) = ($3, $4)
    where id = $1
    returning id, true as updated
), i as (
    insert into teammates (id, email, avatar, timezone)
    select $1, $2, $3, $4
    where not exists (select 1 from u)
    returning id, false as updated
)
select id, updated from u
union all
select id, updated from i
相关问题