插入新表时更新外键

时间:2012-01-07 18:52:39

标签: sql postgresql

我有表A(id)。

我需要

  • 创建表B(id)
  • 向表A添加一个引用B.id
  • 的外键
  • 对于A中的每一行,在B中插入一行并使用B中新插入的行更新A.b_id

是否可以在不添加B中引用A的临时列的情况下执行此操作?下面的确有效,但我不想做一个临时专栏。

alter table B add column ref_id integer references(A.id);
insert into B (ref_id) select id from A;
update A set b_id = B.id from B where B.ref_id = A.id;
alter table B drop column ref_id;

2 个答案:

答案 0 :(得分:2)

假设:

1)你正在使用postgresql 9.1

2)B.id是一个序列(所以实际上是一个int,默认值为nextval('b_id_seq')

3)当插入B时,你实际上是从A添加其他字段,否则插入是无用的

......我认为这样的事情会起作用:

with n as (select nextval('b_id_seq') as newbid,a.id as a_id  from a),
   l as (insert into b(id) select newbid from n returning id as b_id)
 update a set b_id=l.b_id from l,n where a.id=n.a_id and l.b_id=n.newbid;

答案 1 :(得分:0)

  1. 添加未来的外键列,但没有约束本身:

    ALTER TABLE A ADD b_id integer;
    
  2. 使用值填充新列:

    WITH cte AS (
      SELECT
        id
        ROW_NUMBER() OVER (ORDER BY id) AS b_ref
      FROM A
    )
    UPDATE A
    SET b_id = cte.b_ref
    FROM cte
    WHERE A.id = cte.id;
    
  3. 创建另一个表:

    CREATE TABLE B (
      id integer CONSTRAINT PK_B PRIMARY KEY
    );
    
  4. 使用现有表格的引用列将行添加到新表中:

    INSERT INTO B (id)
    SELECT b_id
    FROM A;
    
  5. 添加FOREIGN KEY约束:

    ALTER TABLE A
    ADD CONSTRAINT FK_A_B FOREIGN KEY (b_id) REFERENCES B (id);