SQL Migrate:使用外键将表拆分为两个表

时间:2016-11-20 03:42:53

标签: sql postgresql migrate

如何将下表转换为具有外键的两个拆分表。

当前表:

  ID  | NAME | VAL1 | VAL2 | VAL3
---------------------------------
1102  | John | 100  | 200  | 300
1103  | Kate | 110  | 210  | 310

目标表:

  ID  | NAME | VAL_ID          ID | VAL1 | VAL2 | VAL3
----------------------         -----------------------
1102  | John |   1              1 | 100  | 200  | 300
1103  | Kate |   2              2 | 110  | 210  | 310

2 个答案:

答案 0 :(得分:1)

好吧。 。 。

create table t1 as 
    select id, name, row_number() over (order by id) as val_id
    from t;

create table t2 as
    select t1.val_id, val1, val2, val3
    from t join
         t1
         on t.name = t1.name;

答案 1 :(得分:1)

我认为没有理由在使用ID时生成VAL_ID,这也是此用例的常见做法。

create table base_table as select id,name from src;
alter table  base_table add primary key (id);

create table values_table as select id,val1,val2,val3 from src;
alter table  values_table add primary key (id);
alter table  values_table add foreign key (id) references base_table(id);

只是为了满足OP:

create table base_table as select id,name,row_number()over(order by id) as val_id from src;
alter table  base_table add primary key (id);
alter table  base_table add unique (val_id);

create table values_table as select row_number()over(order by id) as id,val1,val2,val3 from src;
alter table  values_table add primary key (id);
alter table  values_table add foreign key (id) references base_table(val_id);