Postgresql:'upserting' 使用具有唯一约束的相同 ID 分成两个表

Postgresql: 'upserting' into two tables using the same id with a unique constraint

我有两个 table,一个包含所有热列,一个包含静态列。 static table 具有唯一约束。当唯一约束上的冲突触发时,仅应使用静态 table 中的 ID 更新另一个 table 中的热列。 为了更清楚一些代码:

CREATE TABLE tag (
  id        bigserial PRIMARY KEY
, key  text
, value text
-- UNIQUE (key, value) -- ?
);

CREATE TABLE tag_hotcolumns (
  id        bigserial PRIMARY KEY
, hot  text
, stuff text
);
with s as (
    select id, "key", "value"
    from tag
    where key = 'key1' and value = 'value1'
), i as (
    insert into tag ("key", "value")
    select 'key1', 'value1'
    where not exists (select 1 from s)
    returning id
)
select id
from i
union all
select id
from s

第二个块工作正常,但我无法将返回的 ID 放入 tag_hotcolumns...

的插入语句中

我试过了:

insert into tag_attributes (with s as (
    select id, "key", "value"
    from tag
    where key = 'key1' and value = 'value1'
), i as (
    insert into tag ("key", "value")
    select 'key1', 'value1'
    where not exists (select 1 from s)
    returning id
)
select id, 'hot1', 'stuff1'
from i
union all
select id
from s);

这给了我“包含数据修改语句的 WITH 子句必须在顶层 第 5 行:),我作为(

任何帮助将不胜感激:)

stackexchange 的 dwhitemv 帮助我解决了这个问题。您可以在这里找到解决方案: https://dbfiddle.uk/?rdbms=postgres_13&fiddle=f72cae495e6eed579d904a5c7b48f05b