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

Sav*_*der 0 sql constraints oracle-sqldeveloper

在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)
);
Run Code Online (Sandbox Code Playgroud)

我遇到错误

ORA-00942:表或视图不存在

我已经通过首先创建父表来解决此问题,但是由于它们相互引用,我无所适从,因为在这种情况下必须互相引用。

The*_*ler 5

您可以先创建表,然后创建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);
Run Code Online (Sandbox Code Playgroud)

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

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