在多个查询中使用 postgres CTE

use*_*159 6 sql postgresql common-table-expression

我可以在单个查询中使用 CTE,如下所示

with mycte as (...)
  insert into table1 (col1) select col1 from mycte where col1 in
    (select col1 from mycte)
Run Code Online (Sandbox Code Playgroud)

mycte但是如果我想在多个查询中使用怎么办?我怎样才能让这样的事情发挥作用?

with mycte as (...)
  insert into table1 (col1) select col1 from mycte where col1 in
    (select col1 from mycte),
  insert into table2 (col1) select col1 from mycte where col1 in
    (select col1 from mycte)
Run Code Online (Sandbox Code Playgroud)

Gor*_*off 5

对于多个插入,您可以将它们放入同一个查询中:

with mycte as (...),
     i1 as (
      insert into table1 (col1)
          select col1
          from mycte
          where col1 in (select col1 from mycte)
          returning *
     )
insert into table2 (col1)
    select col1
    from mycte
    where col1 in (select col1 from mycte);
Run Code Online (Sandbox Code Playgroud)


Tho*_*ner 0

CTE 是一种临时视图。如果您想要一个可在多个查询中使用的永久视图,请CREATE VIEW改为使用。