简体   繁体   English

使用自引用外键向表添加行

[英]Adding rows to table with self-referencing foreign key

I've created a table called TableTest with two columns ent and dep . 我创建了一个名为TableTest的表,其中包含两列entdep ent is the primary key and dep is the foreign key which references ent . ent是主键,而dep是引用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. 我必须证明三个值(A1,A2,A3)相互依赖。 A3 is dependent of A1 etc. However when I try to insert a row into my table such as: A3依赖于A1等。但是,当我尝试在表中插入一行时,例如:

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. 我对SQL非常陌生。

ORA-02291: integrity constraint violated - parent key not found ORA-02291:违反完整性约束-找不到父密钥

Any help is greatly appreciated! 任何帮助是极大的赞赏!

First, you need to insert the root value . 首先,您需要插入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; Pablo的答案还可以,但是如果您不想使用null也可以做一些其他事情。 First insert same value for both PK and FK and then insert the relation: 首先为PKFK插入相同的值,然后插入关系:

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 . 最简单的方法是deferred外键约束。 That means that the constraint is checked only when you commit , not after each individual insert . 这意味着仅在您commit时才检查约束,而不是在每个单独的insert之后才检查约束。

Another is to insert all values at the same time (in the same INSERT statement); 另一个是在同一时间(在同一INSERT语句中)插入所有值; 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
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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