我们可以有两个相互的外键参考吗

发布于 2025-01-20 05:06:23 字数 124 浏览 2 评论 0原文

如果两个表A和B需要具有相互的外键参考,则可以在A和B的创建表语句中定义每个外键约束。我试图在PGADMIN中执行此操作,但它显示出错误。我只想验证这是该陈述是对还是错。我怀疑要在子表中添加外键参考。它应该具有父表。有些人可以确认吗?

If two tables A and B need to have mutual foreign key references, each foreign key constraint can be defined in the create table statements for A and B. I am trying to do this in pgAdmin, but its showing error. I want to just verify is this statement is true or false. I have a doubt that in order to add a foreign key reference in child table. It should have the parent table. Can some confirm this ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苏璃陌 2025-01-27 05:06:23

是的,您可以具有共同的外键参考,但是您不能仅使用创建表来定义两个参考。原因是当您定义第一表时,第二个表尚不存在,因此您无法用外键引用它。

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

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

在创建表A上返回此错误

模式错误:错误:关系“ b”不存在

,并且由于未能创建A,因此创建表B还返回一个错误:

模式错误:错误:关系“ A”不存在

,您需要另一个步骤。首先创建表A,然后创建表B,其外键引用表A,然后 add 对表A的外键A。现在表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:///wwwww..db-fiddle.com/fb-fiddle.com/f/gb9vo1fqy1fqy8jjty88888888888888888888888888888888888888888.Q7OQ7OQ7Q7OQ7Q7Q7Q7OQ7Q7COGY1PGDYQ7Q7OQ7Q7COGYQ7OQ7Q7Q7COGO >

Yes you can have mutual foreign key references, but you can't define both of them using only create table. The reason is that when you define the first table, the second table doesn't exist yet, so you can't reference it in a foreign key.

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

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

Returns this error at the create table A:

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

And because A failed to be created, the create table B also returns an error:

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

Instead, you need another step. First create table A, then create table B with its foreign key reference to table A, then add the foreign key to table A. Now that table B exists, you can reference it.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文