【发布时间】:2016-10-18 11:49:30
【问题描述】:
如何在有效的 Postgres SQL 查询中编写以下内容:
with foo as (select * from ...)
insert into bar select * from foo
insert into baz select * from foo
【问题讨论】:
标签: sql postgresql common-table-expression
如何在有效的 Postgres SQL 查询中编写以下内容:
with foo as (select * from ...)
insert into bar select * from foo
insert into baz select * from foo
【问题讨论】:
标签: sql postgresql common-table-expression
您可以使用 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。这是正常的用例 - 例如,您可以从插入中获取序列号。【讨论】:
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;
【讨论】: