如何在两个 psql 事务中使用相同的临时 table?

How to use the same temporary table in two psql transactions?

我正在尝试通过几个步骤执行非常基本的操作:

  1. SELECT 数据来自 table1
  2. 使用我选择的 table 中的 id 列从 table2
  3. 中删除数据
  4. 将步骤 1 中选择的 table 插入 table2

我认为这会奏效

begin;

with temp as (
  select id
  from table1
)

delete from table2
where id in (select id from temp);

insert into table2 (id)
select id from temp;

commit;

但我收到一条错误消息,提示我在插入步骤中未定义温度?

我发现的其他 post this one 但它并没有真正回答我的问题。

想法?

来自 Postgres 文档:

WITH provides a way to write auxiliary statements for use in a larger query. These statements, which are often referred to as Common Table Expressions or CTEs, can be thought of as defining temporary tables that exist just for one query.

如果您需要一个临时 table 用于多个查询,您可以改为:

begin;

create temp table temp_table as (
  select id
  from table1
);

delete from table2
where id in (select id from temp_table);

insert into table2 (id)
select id from temp_table;

commit;