postgresSql删除中间表,但将链接关系替换为单个关系
我有三张桌子。表1、表2、表3 表2具有table1Id关系,表3具有table2Id关系 我想删除表2,但我想保持表3和表1之间的链接关系。也就是说,将表2与表1的关系移动到表3中的新列,然后删除表3和表2之间的关系,最后删除表2 类似这样的内容:postgresSql删除中间表,但将链接关系替换为单个关系,sql,postgresql,Sql,Postgresql,我有三张桌子。表1、表2、表3 表2具有table1Id关系,表3具有table2Id关系 我想删除表2,但我想保持表3和表1之间的链接关系。也就是说,将表2与表1的关系移动到表3中的新列,然后删除表3和表2之间的关系,最后删除表2 类似这样的内容: alter table "db"."Table 3" add column "table1Id" bigint not noll references "db".&qu
alter table "db"."Table 3" add column "table1Id" bigint not noll references "db"."Table 1"("id") on delete cascade;
-- update new field to point to the tbale1Id where table 2 previously pointed to
alter table "db"."Table 3" drop column "table2Id";
drop table "db"."Table 2";
之前的数据:
表1:(id:337),(id:7)
表2:(id:214,表1ID:337),(id:16,表1ID:7)
表3:(id:9,表2ID:214),(id:998,表2ID:16)
迁移后需要的数据:
表1:(id:337),(id:7)
表3:(id:9,表1ID:337),(id:998,表1ID:7)
考虑以下迁移脚本:
-- add the new column
alter table table3 add column table1_id bigint references table1(id) on delete cascade;
-- initialize the content
update table3 t3 set table1_id = (
select table1_id from table2 t2 where t2.id = t3.table2_id
);
-- make the column not nullable
alter table table3 alter column table1_id set not null;
-- cleanup
alter table table3 drop column table2_id;
drop table table2_id;
注意:由于该表已包含记录,因此不能将列创建为非空
;您需要首先填充它,然后应用notnull
约束
:
运行脚本后表3
的内容:
id | table1_id
--: | --------:
9 | 337
998 | 7
id |表1| id
--: | --------:
9 | 337
998 | 7
哦,对了。NOTNULL约束只能在更新后进行。我试试这个。谢谢update语句中不需要where子句?因此它将更新表3的所有记录?@RasmusPuls:update语句使用相关子查询在
table2
:中查找相关记录,其中t2.id=t3.table2\u id
。这将使用table2
中相关记录的table1\u id
更新table3
中的所有记录。