如何在有效的Postgres SQL查询中编写以下内容:
with foo as (select * from ...)
insert into bar select * from foo
insert into baz select * from foo
答案 0 :(得分:4)
如果您想在一个语句中使用CTE,则可以使用CTE:
with foo as (
select * from ...
),
b as (
insert into bar
select * from foo
returning *
)
insert into baz
select * from foo;
注意:
insert
。select *
明确指定列名。这很重要,因为两个表中的列可能不匹配。returning
/ update
/ insert
delete
。这是正常的用例 - 例如,您可以从插入中获取序列ID。答案 1 :(得分:0)
with
子句的范围只是一个查询。我能想到的唯一解决方案是创建一个视图,并在插入完成后删除它。它不像CTE那样完全是短暂的,但这里没有数据重复 - 只是一个(相对)便宜的DDL操作:
-- Create the view
CREATE VIEW foo AS SELECT * FROM ...;
-- Perform the inserts
INSERT INTO bar SELECT * FROM foo;
INSERT INTO baz SELECT * FROM foo;
-- Drop the view when you're done
DROP VIEW foo;