gpt4 book ai didi

sql - 创建两个外键相互引用的表

转载 作者:行者123 更新时间:2023-12-03 23:21:02 26 4
gpt4 key购买 nike

在 Oracle SQL 中,SQL Developer:我试图创建两个表,每个表都有一个引用另一个表的主键的外键。

使用我的逻辑,我无法设置外键引用,因为另一个表尚不存在。

这是我如何构建它的一般想法:

CREATE TABLE table1 
(
column1 datatype PRIMARY KEY NOT NULL,
column2 datatype NOT NULL,
column3 datatype NOT NULL,

CONSTRAINT fk_keyname
FOREIGN KEY (colmn3)
REFERENCES otherTable (column3)
);

CREATE TABLE table2
(
column1 datatype PRIMARY KEY NOT NULL,
column2 datatype NOT NULL,
column3 datatype NOT NULL,

CONSTRAINT fk_keyname2
FOREIGN KEY (colmn3)
REFERENCES otherTable2 (column3)
);

我收到一个错误

ORA-00942: table or view does not exist



我之前通过先创建父表来解决这个问题,但是由于它们都相互引用,因此我在这里需要做的事情不知所措,因为在这种特殊情况下必须相互引用。

最佳答案

您可以先创建表,然后创建 FK。例如:

create table table1 (
column1 int primary key not null,
column2 int not null,
column3 int not null
);

create table table2 (
column1 int primary key not null,
column2 int not null,
column3 int not null,
constraint fk2
foreign key (column3)
references table1 (column1)
);

alter table table1 add constraint fk1
foreign key (column3)
references table1 (column1);

即使将创建表,您也无法在其中插入数据,因为约束将阻止您创建不指向其他 [不存在] 行的行。为了插入数据,您需要将约束创建为“可延迟”。这是改进后的 SQL 脚本:
create table table1 (
column1 int primary key not null,
column2 int not null,
column3 int not null
);

create table table2 (
column1 int primary key not null,
column2 int not null,
column3 int not null,
constraint fk2
foreign key (column3)
references table1 (column1) deferrable initially deferred
);

alter table table1 add constraint fk1
foreign key (column3)
references table1 (column1) deferrable initially deferred;

现在,确保在事务边界之间插入所有相关表的行。现在将检查约束 在交易结束时才而不是在每个插入/修改/删除的行上。

关于sql - 创建两个外键相互引用的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58278790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com