【问题标题】:How to Insert into third table on conflict of two tables composite key in PostgreSQL?如何在 PostgreSQL 中的两个表复合键冲突时插入第三个表?
【发布时间】:2021-09-22 05:01:07
【问题描述】:

有一个临时表 active_data_staging,它每 5 分钟被截断并插入一次,但是其中的许多记录已经存在于 final table active_data 中。因此,为了仅从 active_data_staging 表 中提取我的 final table active_data 记录,我在复合键冲突时运行插入查询。

现在,一个要求来了,我只需要每 5 分钟将新行获取到第三个表 active_data_fresh,它将被截断并仅以相同的刷新频率插入新数据。

示例

现在:我的暂存行有 145 行(130 行旧,15 行新)。我的决赛桌有 1000 行(都是旧的)。我们从 staging 中插入 15 个新行,仅将其插入到最终表中,使其达到 1015 行。

期望:必须有另一个表,只有在截断上次运行的所有内容后才会加载 15 行。

我怎样才能做到这一点?

现有的insert on conflict查询如下:

insert into dev.active_data
(name, mobile, unique_identity, address, city)
select name, mobile, unique_identity, address, city
from dev.data_staging
on conflict on constraint unique_people do nothing

这里,unique_people 约束如下:

ALTER TABLE dev.active_data
   ADD CONSTRAINT unique_people UNIQUE (mobile, unique_identity);

【问题讨论】:

    标签: sql postgresql select insert constraints


    【解决方案1】:

    Postgres 允许在 CTE 中使用 DML。您可以使用它将当前的 INSERT 转换为 CTE 并返回刚刚插入的内容。然后为主创建一个新表的 INSERT。这是有效的,因为当 Postgres 看到重复项时,它什么也不做——包括不返回指示的值。所以:(见demo

    with merged_data as 
        (insert into active_data
                 (name, mobile, unique_identity, address, city)
          select name, mobile, unique_identity, address, city
            from data_stage
              on conflict on constraint unique_people do nothing
          returning *
        ) 
    insert into new_active(name, mobile, unique_identity, address, city) 
      select name, mobile, unique_identity, address, city
        from merged_data; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      • 2010-10-04
      • 1970-01-01
      相关资源
      最近更新 更多