在多个查询中使用相同的 Postgres WITH

maf*_*afu 6 postgresql

我想WITH在多个查询中使用相同的。

WITH x AS (INSERT ... RETURNING id)
INSERT INTO t2 VALUES (x);
INSERT INTO t3 VALUES (x);
Run Code Online (Sandbox Code Playgroud)

我该怎么做?我是否必须创建一个临时表?

a_h*_*ame 16

您可以链接多个执行 INSERT 的 CTE:

with x (id) as (
  insert into ... 
  returning id
), t2_insert as (
  insert into t2 (id)
  select id
  from x
)
insert into t3
select id
from x;
Run Code Online (Sandbox Code Playgroud)