简体   繁体   中英

Adding rows to table with self-referencing foreign key

I've created a table called TableTest with two columns ent and dep . ent is the primary key and dep is the foreign key which references ent . I create the table using:

CREATE TABLE TableTest (
  ent varchar(2) NOT NULL,
  dep varchar(2),
  PRIMARY KEY (ent),
  FOREIGN KEY (dep) REFERENCES TableTest(ent)
);

I must show that the three values (A1,A2,A3) depend on one another. A3 is dependent of A1 etc. However when I try to insert a row into my table such as:

INSERT INTO TableTest(ent, dep)
  VALUES ('A1','A3');

I get the following error and after doing research I'm still stuck on how to get by this. I'm very new to SQL.

ORA-02291: integrity constraint violated - parent key not found

Any help is greatly appreciated!

First, you need to insert the root value .

> insert into TableTest values ('A1', null);
> insert into TableTest values ('A3', 'A1');

Pablo's answer is okay but you can do something alse too if you don't want to have null s; First insert same value for both PK and FK and then insert the relation:

insert into TableTest values ('A1', 'A1');
insert into TableTest values ('A3', 'A1');

There are cases, just like the one you posted, where circular references (which are absolutely fine by the way, no logical issue there) conflict with the normal way relational integrity constraints work. This is because relational integrity has some "directional" features (primary key comes first, then foreign key) even though dependencies can be circular, as you have seen.

There are several work-arounds. The easiest is to make the foreign key constraint deferred . That means that the constraint is checked only when you commit , not after each individual insert .

Another is to insert all values at the same time (in the same INSERT statement); for example:

insert into tabletest(ent, dep)
  select 'A1', 'A3' from dual union all
  select 'A3', 'A2' from dual union all
  select 'A2', 'A1' from dual
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM