多个WITH / CTE的多个插入

时间:2017-07-06 15:12:32

标签: sql postgresql

我有一张这样的表:

CREATE TABLE mytable
(
  col1 character varying(50),
  mydate timestamp without time zone
);

我想在此表中插入数据,但我还希望存储源代码中的最大ID:

insert into mytable (select myid, col1, mydate from sourcetable);

我在mytable中没有myid列,后来我不能问这样的事情:select max(myid) from sourcetable因为我正在获取快照,而源表是一个事务表(数百条新记录由第二)所以我需要从该快照中获取最大ID

我试过这样的事情:

with query1 as (select myid, col1, mydate from sourcetable),
query2 as (select max(myid) id from query1)
insert into mytable (select co1, mydate from query1);
update anothertable set value=(select myid from query2) where col2='avalue';

但是我收到了这个错误:

ERROR:  relation "query2" does not exist
LINE 1: update anothertable set value=(select myid from query2) wher...

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:1)

问题是您在CTE之后有两个查询。只有一个。 CTE连接到查询。所以,只需添加另一个CTE。像这样:

with query1 as (
      select myid, col1, mydate
      from sourcetable
     ),
     query2 as (
      select max(myid) as id
      from query1
     ),
     i as (
      insert into mytable   -- You should really list the columns here
          select co1, mydate
          from query1
     )
update anothertable
    set value = (select myid from query2)
    where col2 = 'avalue';