我有表 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;
最佳答案
假设:
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;
关于sql - 插入新表时更新外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8772139/