可写的公用表表达式和多个插入语句 [英] writeable common table expression and multiple insert statements
本文介绍了可写的公用表表达式和多个插入语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在有效的Postgres SQL查询中编写以下内容:
How do I write the following in a valid Postgres SQL query:
with foo as (select * from ...)
insert into bar select * from foo
insert into baz select * from foo
推荐答案
如果要在一个语句中全部使用,则可以使用CTE:
You can use CTEs, if you want this all in one statement:
with foo as (
select * from ...
),
b as (
insert into bar
select * from foo
returning *
)
insert into baz
select * from foo;
注意:
- 您应在列列表中添加
插入
。 - 应为明确指定列名
选择*
。这很重要,因为两个表中的列可能不匹配。 - 我总是将
returning
与update一起使用
/插入
/删除
在CTE中。这是正常的用例-例如,您可以从插入内容中获取序列ID。
- You should include column lists with
insert
. - You should specify the column names explicitly for the
select *
. This is important because the columns may not match in the two tables. - I always use
returning
withupdate
/insert
/delete
in CTEs. This is the normal use case -- so you can get serial ids back from an insert, for instance.
这篇关于可写的公用表表达式和多个插入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文