外键是否始终引用另一个表中的唯一键?

rat*_*tsy 22 oracle key parent

子表中的外键(单列)是否可能引用具有某些重复值的父键?

Bil*_*win 25

根据SQL标准,外键必须引用父表的主键或唯一键.如果主键具有多个列,则外键必须具有相同的列数和顺序.因此,外键引用父表中的唯一行; 没有重复.


你的评论:

如果T.A是主键,则不能有任何重复项.任何主键必须唯一且非空.因此,如果子表具有引用父主键的外键,则它必须匹配非null的唯一值,因此在父表中只引用一行.在这种情况下,您不能创建引用多个父行的子行.

可以创建外键列为NULL的子行,在这种情况下,它不引用父表中的行.

  • @ratsy:外键必须始终引用声明为PRIMARY KEY或UNIQUE的一列或多列.(除非你使用的是MySQL.但是你仍然应该只在MySQL中定位PRIMARY KEY或UNIQUE列.搜索http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints. html表示"系统不强制要求引用的列为UNIQUE".) (2认同)

Ode*_*ded 7

不,这是不可能的.

在表上定义外键约束时,表示外表上只有一个对应的键.如果在外表上存在倍数,那意味着什么?

维基百科在外键条目上有这个定义:

外键是关系表中与另一个表的候选键匹配的字段

候选键在表格中是唯一的.


Jon*_*ler 7

是的,外键可能引用具有重复值的列.

如果主键使用非唯一索引并且在创建时未进行验证,则会发生这种情况.(但我在现实生活中从未见过这样的情况.正如@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);
Run Code Online (Sandbox Code Playgroud)