2012-01-07 117 views
0

我有表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; 
+0

你打我。太多的IDS。 – 2012-01-07 19:34:04

+0

問題太混亂了嗎? – 2012-01-07 19:41:30

+1

你的問題沒有意義。你真的想要達到什麼目標? – 2012-01-07 19:43:39

回答

1

假設:

1)你使用PostgreSQL 9.1

2)B.id是串行(所以實際上一個與NEXTVAL( 'b_id_seq' 的默認值INT)

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; 
+0

爲什麼3(插入無用,如果沒有其他列)?好好考慮CTE,我會試試看。 – 2012-01-07 20:36:43

+0

考慮到SQL插入B(ref_id)'和目標是擺脫ref_id,如果沒有B.ref_id,你會插入哪些列? – 2012-01-07 21:03:14

+0

除B.id外無其他。 – 2012-01-07 21:26:26

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);