Reputation: 33
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!
Upvotes: 3
Views: 1938
Reputation:
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
;
Upvotes: 1
Reputation: 7890
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');
Upvotes: 1
Reputation: 181390
First, you need to insert the root value
.
> insert into TableTest values ('A1', null);
> insert into TableTest values ('A3', 'A1');
Upvotes: 5