我们可以有两个相互外键引用吗

Can we have two mutual foreign key references

如果两个tables A和B需要有相互的外键引用,每个外键约束可以在A和B的create table语句中定义。我正在尝试做这在 pgAdmin 中,但显示错误。我只想验证这个陈述是对还是错。我怀疑为了在子 table 中添加外键引用。它应该有父 table。有人可以证实这一点吗?

是的,您可以拥有相互外键引用,但您不能仅使用 create table 来定义它们。原因是当你定义第一个table时,第二个table还不存在,所以你不能在外键中引用它。

create table A (id serial primary key, Bid serial references B);

create table B (id serial primary key, Aid serial references A);

Returns 创建时出现此错误 table A:

Schema Error: error: relation "b" does not exist

又因为A创建失败,创建tableB也returns报错:

Schema Error: error: relation "a" does not exist

相反,您还需要一个步骤。首先创建 table A,然后创建 table B,其外键引用 table A,然后 添加 外键到 table A. 现在table B已经存在,可以引用了

create table A (id serial primary key);

create table B (id serial primary key, Aid serial references A);

alter table A add Bid serial references B;

https://www.db-fiddle.com/f/gb9vo1fQy8Jty1pGdn8Q7o/0