来自多个 WITH/CTE 的多个插入

Nat*_*izz 1 sql postgresql

我有一张这样的表:

CREATE TABLE mytable
(
  col1 character varying(50),
  mydate timestamp without time zone
);
Run Code Online (Sandbox Code Playgroud)

我想向这个表插入数据,但我也想从我的源中存储最大 id:

insert into mytable (select myid, col1, mydate from sourcetable);
Run Code Online (Sandbox Code Playgroud)

我在 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';
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:

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

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

Gor*_*off 5

问题是您在 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';
Run Code Online (Sandbox Code Playgroud)