在 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: 表或视图不存在
我之前已经通过首先创建父表解决了这个问题,但是由于它们都相互引用,所以我对这里需要做的事情感到不知所措,因为在这种特殊情况下必须相互引用。
您可以先创建表,然后创建 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);
即使将创建表,您也无法在其中插入数据,因为约束将阻止您创建不指向其他[不存在]行的行。为了插入数据,您需要将约束创建为“可延迟”。这是improvedSQL脚本:
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;
现在,请确保在事务边界之间插入所有涉及的表的行。现在将检查约束仅在交易结束时而不是在每个插入/修改/删除的行上。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)