sql - 插入新表时更新外键

标签 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;

最佳答案

假设:

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/

相关文章:

mysql - 通过 shell 将 mysql 数据库结构复制到另一个数据库不起作用

sql - Oracle 同义词问题

python - 使用 SQLAlchemy 获取表中的行数

node.js - Sequelize插入连接表(多对多)

sql - 如何在单个查询中使用 count ,'like' 和 group by?

sql - 创建表...就像不工作

sql - 累计差异

validation - to_tsquery() 验证

java - Spring Boot - 外键 PostgreSQL 数据库中的空值

sql - PostgreSQL 字符串搜索部分模式删除无关字符