简体   繁体   English

引用复合主键的一列作为外键

[英]Referencing one column of a composite primary key as a foreign key

In the table A , I've got a composite of 3 fields as a primary key and in the table B I've got one of the composite (which is not unique). table A ,我得到了3个字段作为primary key的组合,在table B我有一个复合(不是唯一的)。 I'd like to reference with the table A to ease the delete (with ON DELETE CASCADE ). 我想引用table A来简化delete (使用ON DELETE CASCADE )。

So, am I compelled to put the other two fields in the table B and reference with this composite or is there another solution? 那么,我是否被迫将其他两个字段放在表B中并使用这个composite引用,还是有其他解决方案?

If you want to create a foreign key constraint between the two tables, the child table would have to have all the columns that comprise the primary key constraint on the parent table (which is one of the reasons that I would discourage the use of composite primary keys). 如果要在两个表之间创建外键约束,子表必须具有构成父表的主键约束的所有列(这是我不鼓励使用复合主表的原因之一)键)。 If you want Oracle to automatically delete a child row when then parent row is deleted, you need a foreign key constraint with ON DELETE CASCADE . 如果希望Oracle在删除父行时自动删除子行,则需要使用ON DELETE CASCADE的外键约束。 So your options are 所以你的选择是

  • Add all the columns that comprise the primary key of the parent to the child. 将包含父级主键的所有列添加到子级。
  • Redesign the parent table so that there is a single-column primary key (presumably a synthetic key) and use that in the child table. 重新设计父表,以便有一个单列主键(可能是一个合成键)并在子表中使用它。
  • Write code that implements the deletes yourself. 编写自己实现删除的代码。

You could create a new single-column (probably sequence-generated) primary key in table A and make the existing composite key a unique key instead of a primary key. 您可以在表A中创建新的单列(可能是序列生成的)主键,并使现有的组合键成为唯一键而不是主键。 Then reference your new primary key from table B. 然后从表B中引用新的主键。

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

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