首页 > 解决方案 > 使用一个 cte postgres 进行多次插入

问题描述

我是postgres的初学者。在做一个虚拟项目时,我遇到了这个问题。

我有两张表,可以说 t1 和 t2。t1 与 t2 有 1->Many 关系。

我正在尝试编写一个 SQL 语句,它首先在 t1 中插入数据,然后使用 t1 中的 id 在 t2 中插入多行。

像这样的东西。

WITH ins AS (
    INSERT INTO t1(t1_col) 
    VALUES (4)
    RETURNING t1_id
)
INSERT INTO t2(t1_id, t2_col) VALUES (ins.t1_id, 3), (ins.t1_id, 4)...

t1 结构 -> (t1_id primary_key 序列,t1_col 整数)。

t2 结构 -> (t2_id primary_key 序列,t1_id 整数,t2_col 整数)。

这样做的正确方法是什么。

先感谢您。

标签: postgresqlcommon-table-expression

解决方案


除了插入 withVALUES子句,您可以插入SELECT. 一般来说,它将是:

WITH ins AS (
  INSERT INTO table1(target columns)
  VALUES (some values) -- or -- SELECT something FROM somewhere
  RETURNING some_id
)
INSERT INTO table2(target columns)
SELECT ins.some_id, other columns or expressions
FROM ins;

多行的变体(固定列表)

WITH ins AS (
  INSERT INTO table1(target columns)
  VALUES (some values) -- or -- SELECT something FROM somewhere
  RETURNING some_id
)
INSERT INTO table2(target columns)
SELECT ins.some_id, UNNEST(ARRAY[3,4,...])
FROM ins;

其中 3,4.... 是值列表


推荐阅读