可写的公用表表达式和多个插入语句

Mic*_*ent 4 sql postgresql common-table-expression

如何在有效的Postgres SQL查询中编写以下内容:

with foo as (select * from ...)
insert into bar select * from foo
insert into baz select * from foo
Run Code Online (Sandbox Code Playgroud)

Gor*_*off 6

如果要在一条语句中全部使用,可以使用CTE:

with foo as (
      select * from ...
     ),
     b as (
      insert into bar
          select * from foo
          returning *
     )
insert into baz
    select * from foo;
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 您应在列列表中添加insert
  • 您应该指定列名明确select *。这很重要,因为两个表中的列可能不匹配。
  • 我总是用returningupdate/ insert/ delete在热膨胀系数。这是正常的用例-例如,您可以从插入中获取序列号。