在多个查询中使用postgres CTE

时间:2018-10-22 08:48:57

标签: 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 in
    (select col1 from mycte),
  insert into table2 (col1) select col1 from mycte where col1 in
    (select col1 from mycte)

2 个答案:

答案 0 :(得分:1)

CTE是临时视图。如果您希望可以在多个查询中使用的永久视图,请改用CREATE VIEW

答案 1 :(得分:0)

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

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