繁体   English   中英

使用一个 cte postgres 进行多次插入

[英]Multiple inserts using one 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 integer,t2_col 整数)。

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

先感谢您。

除了使用VALUES子句插入之外,您还可以插入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.... 是值列表

一个匿名的 plpgsql 块就可以了。

do language plpgsql
$$
declare
  t1id t1.t1_id%type;
begin 
  INSERT INTO t1(t1_col) VALUES (4) RETURNING t1_id INTO t1id;
  INSERT INTO t2(t1_id, t2_col) 
  VALUES (t1id, 3), (t1id, 4)...;
end;
$$;

这将在单个语句中完成。

WITH ins AS (
    INSERT INTO t1(t1_col) 
    VALUES (4)
    RETURNING t1_id
)
INSERT INTO t2(t1_id, t2_col) 
SELECT ins.t1_id, v.t2_col
  from ins
 cross join (VALUES (3), (4)) as v(t2_col)
;

如果您从宿主语言运行它并且可以将t2值作为数组传递,请发表评论,因为这可以简化。

我会像这样构建它以与宿主语言一起使用:

with invars as (
  select $1 as t1_col, $2::text[] as t2_cols
), ins as (
  insert into t1 (t1_col)
  select t1_col 
    from invars
  returning t1_id 
)
insert into t2 (t1_id, t2_col)
select ins.t1_id, unnest(invars.t2_cols) as t2_col
  from ins
 cross join invars;

然后,从主机,我将t1_col和一个t2_col值数组作为参数传递给查询。

不需要 CTE 或变量,您可以使用lastval()获取最后生成的标识(或序列)值:

INSERT INTO t1(t1_col) 
VALUES (4);

INSERT INTO t2(t1_id, t2_col) 
VALUES 
(lastval(), 3), 
(lastval(), 4),
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM