【问题标题】:insert data from staging table to 2 tables by reusing postgres index or bigserial通过重用 postgres 索引或 bigserial 将数据从临时表插入到 2 个表
【发布时间】:2021-12-13 07:14:12
【问题描述】:

我有 3 张桌子:

CREATE TABLE stage
(
  a1 text,
  b2 text,
  c3 text,
  d4 text,
  e5 text
);

CREATE TABLE main
(
  id bigserial PRIMARY KEY,
  a1 text,
  b2 text,
  c3 text
);

CREATE TABLE secondary (
  id bigserial PRIMARY KEY,
  mainid bigint,
  d4 text,
  e5 text,
  CONSTRAINT secondary_fkey FOREIGN KEY(mainid) REFERENCES main(id)
);

我想一次将来自stage 的数据插入mainsecondary,但我不太确定如何通过在main 中重用生成的bigserial 来做到这一点。我正在尝试with query,但secondary 中的行数(指数)比预期的要多。

dbfiddle

WITH tmp AS (
  INSERT INTO
    main (a1, b2, c3)
  SELECT
    a1,
    b2,
    c3
  FROM
    stage RETURNING id
)
INSERT INTO
  secondary (mainid, d4, e5)
SELECT
  tmp.id,
  stage.d4,
  stage.e5
FROM
  tmp,
  stage;

【问题讨论】:

    标签: sql postgresql postgres-10


    【解决方案1】:

    您的问题是您在最后的INSERT 语句中创建的交叉连接与FROM tmp, stage;。如果您在 stage 表中有 10 行,这将生成 100 行而不是您想要的 10 行。

    如果(a1, b2, c3) 唯一标识stage 中的一行,您可以将它们用于正确的连接条件:

    WITH tmp AS (
      INSERT INTO main (a1, b2, c3)
      SELECT a1, b2, c3
      FROM stage 
      RETURNING *
    )
    INSERT INTO secondary (mainid, d4, e5)
    SELECT tmp.id,
           stage.d4,
           stage.e5
    FROM tmp 
      JOIN stage 
        on tmp.a1 = stage.a1 
       and tmp.b2 = stage.b2 
       and tmp.c3 = stage.c3;
    

    如果这不可行(因为有重复),您可以使用nextval()

    在插入之前插入之前为main 表生成新ID。
    with stage_with_mainid as (
      select nextval(pg_get_serial_sequence('main', 'id')) as mainid,
             a1, b2, c3, d4, e5
      from stage       
    ), insert_main as (
      insert into main (id, a1, b2, c3) --<< this provides the generated new ID explictely
      select mainid, a1, b2, c3
      from stage_with_mainid
    )
    insert into secondary (mainid, d4, e5)
    select mainid, d4, e5
    from stage_with_mainid;
    

    【讨论】:

      猜你喜欢
      • 2015-05-04
      • 2022-01-24
      • 2018-06-26
      • 2021-10-04
      • 2012-07-31
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多