Sql 在多个查询中使用postgres CTE

Sql 在多个查询中使用postgres CTE,sql,postgresql,common-table-expression,Sql,Postgresql,Common Table Expression,我可以在这样一个查询中使用CTE with mycte as (...) insert into table1 (col1) select col1 from mycte where col1 in (select col1 from mycte) 但是如果我想在多个查询中使用mycte,该怎么办?我怎样才能做这样的工作 with mycte as (...) insert into table1 (col1) select col1 from mycte where col1

我可以在这样一个查询中使用CTE

with mycte as (...)
  insert into table1 (col1) select col1 from mycte where col1 in
    (select col1 from mycte)
但是如果我想在多个查询中使用
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)

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

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

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);

如果希望数据在语句中持久化,我认为需要使用临时表。cte是一次性的,并且是查询的本地表。改为创建一个视图。您能举一个临时表或视图的例子吗?是否可以创建一个不在postgres函数之外持久的临时视图?因此,我可以在该函数/事务中的多个查询中使用它,但不能在外部使用。我认为在PostgreSQL中,您可以选择一个数组,然后从该数组中选择。