如果我在SQL中使用ForeignKey,它是否总是必须使用我引用的表中的所有列?
所以,例如。
Table1
subjectID名字姓氏电子邮件
Table2:
汽车图书外键(SubjectID)
我只能使用一列作为外键,还是必须总是获取所有列?
谢谢!
发布于 2010-08-24 21:41:53
外键必须引用唯一键,通常是主键。
因此,如果父表的主键中只有一列,那么这是唯一需要在外键中使用的列。如果父表有一个复合主键(即多个列),那么您需要在子表中包含所有这些列。
这就是为什么人们倾向于避免使用复合主键而倾向于使用代理键和唯一约束的原因之一。
下面是一个有效的示例(使用Oracle,但它在所有RDBMS版本上都是一样的)。首先,我们创建一个具有单列主键的父表,并从子表引用它。
SQL> create table t1 (id number not null, seqno number not null)
2 /
Table created.
SQL> alter table t1 add constraint t1_pk primary key (id)
2 /
Table altered.
SQL> create table t2 (id number not null, t1_id number not null, whatever varchar2(10) )
2 /
Table created.
SQL> alter table t2 add constraint t2_t1_fk foreign key (t1_id)
2 references t1 (id)
3 /
Table altered.
SQL>
很简单。但是如果我们丢弃这些键并给T1一个复合主键,事情就会分崩离析……
SQL> alter table t2 drop constraint t2_t1_fk
2 /
Table altered.
SQL> alter table t1 drop constraint t1_pk
2 /
Table altered.
SQL> alter table t1 add constraint t1_pk primary key (id, seqno)
2 /
Table altered.
SQL> alter table t2 add constraint t2_t1_fk foreign key (t1_id)
2 references t1 (id)
3 /
references t1 (id)
*
ERROR at line 2:
ORA-02270: no matching unique or primary key for this column-list
SQL>
我们需要向子表添加匹配的第二列,并将其包含在外键定义中:
SQL> alter table t2 add t1_seqno number
2 /
Table altered.
SQL> alter table t2 add constraint t2_t1_fk foreign key (t1_id, t1_seqno)
2 references t1 (id, seqno)
3 /
Table altered.
SQL>
发布于 2010-08-24 20:52:30
只能将选定的列或所有列的组合用作外键。
发布于 2010-08-24 23:20:14
简而言之,一个表的主键在其他表中用作外键。我们不使用一个表的所有列作为其他表中的外键(这将再次导致冗余,这也是有问题的)。
此外,您还可以在其他表中使用主键、唯一键、主键+‘某些其他列’等作为外键。
https://stackoverflow.com/questions/3556685
复制相似问题