创建两个表,它们的外键互相引用

问题描述 投票:0回答:2

在oracle SQL中,sql开发人员

我正在尝试创建两个表,每个表都有一个引用其他主键的外键。使用我的逻辑,我无法设置外键引用,因为另一个表尚不存在。这里是我如何构造它的一般想法:

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:表或视图不存在。我已经通过首先创建父表来解决此问题,但是由于它们相互引用,我无所适从,因为在这种情况下必须互相引用。

sql constraints oracle-sqldeveloper
2个回答
1
投票

从技术角度来看,可以创建没有外键约束的第一个表,然后创建第二个表(具有外键),最后将外键约束添加到第一个表。

但是您遇到的问题确实表示设计问题。它还预示了您尝试填充表时将要解决的问题:由于使用交叉外键,因此您将无法在表中使用INSERT记录,除非您执行一些复杂的操作,例如暂时禁用其中之一。约束,在两个表中插入,更新第一个表,然后启用约束。

您的问题并没有为我提供足够的上下文来提出替代设计的建议,但是,根据经验,肯定存在更好的解决方案。它可以包括有一个表而不是两个表(如果要处理1-1关系),或者如果有N-M关系,则要有第三个表充当桥表。]


0
投票

您可以先创建表,然后再创建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);

即使将创建表,您也将无法在其中插入数据,因为约束将阻止您创建不指向另一[不存在]行的行。为了插入数据,您需要将约束创建为“可延迟”。这是improved 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;

现在,请确保在事务边界之间插入所有涉及表的行。现在将<检查约束,而不是在每个插入/修改/删除的行中都检查约束。

© www.soinside.com 2019 - 2024. All rights reserved.