【发布时间】:2012-02-01 03:03:00
【问题描述】:
子表中的外键(单列)是否不可能引用具有一些重复值的父键?
【问题讨论】:
子表中的外键(单列)是否不可能引用具有一些重复值的父键?
【问题讨论】:
根据 SQL 标准,外键必须引用父表的主键或唯一键。如果主键有多个列,则外键必须具有相同的列数和顺序。因此外键引用父表中的唯一行;不能有重复。
你的评论:
如果T.A 是主键,那么不,您不能有任何重复项。任何主键都必须是唯一且非空的。因此,如果子表有一个引用父表主键的外键,它必须匹配一个非空的唯一值,因此只引用父表中的一行。在这种情况下,您不能创建引用多个父行的子行。
您可以创建一个外键列为 NULL 的子行,在这种情况下,它不会引用父表中的任何行。
【讨论】:
oracle,所以我没有提出 InnoDB 的非标准行为。即使在使用 InnoDB 时,我也强烈建议不要引用非唯一的父行,因为这样很容易混淆。
不,这是不可能的。
当你在一张表上定义外键约束时,这意味着在外表上只有一个对应的键。如果外表上存在多个倍数,那意味着哪一个?
维基百科在Foreign key 条目上有这个定义:
外键是关系表中与另一个表的候选键匹配的字段
候选键在表中是唯一的。
【讨论】:
是的,外键可以引用具有重复值的列。
如果主键使用非唯一索引并且在创建时未经过验证,则可能会发生这种情况。 (但我在现实生活中从未见过这样的情况。正如@Bill Karwin 指出的那样,这会非常令人困惑。所以这可能不是你真正需要担心的情况。)
--Create a table with two duplicate rows
create table test1(a number);
insert into test1 values(1);
insert into test1 values(1);
commit;
--Create a non-unique index
create index test1_index on test1(a);
--Use the non-unique index for the primary key, do not validate
alter table test1 add constraint test1_pk primary key (a)
using index test1_index novalidate;
--Build another table with a foreign key to TABLE1
create table test2(a number,
constraint test2_fk foreign key (a) references test1(a));
--Inserting a value that refers to the duplicate value still works.
insert into test2 values(1);
commit;
--The foreign key still works:
--ORA-02291: integrity constraint (TEST2_FK) violated - parent key not found
insert into test2 values(2);
--The primary key works as expected, but only for new values:
--ORA-00001: unique constraint (TEST1_PK) violated
insert into test1 values(1);
【讨论】: