首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >SQL ForeignKey列

SQL ForeignKey列
EN

Stack Overflow用户
提问于 2010-08-24 12:31:04
回答 3查看 764关注 0票数 1

如果我在SQL中使用ForeignKey,它是否总是必须使用我引用的表中的所有列?

所以,例如。

Table1

subjectID名字姓氏电子邮件

Table2:

汽车图书外键(SubjectID)

我只能使用一列作为外键,还是必须总是获取所有列?

谢谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-08-24 13:41:53

外键必须引用唯一键,通常是主键。

因此,如果父表的主键中只有一列,那么这是唯一需要在外键中使用的列。如果父表有一个复合主键(即多个列),那么您需要在子表中包含所有这些列。

这就是为什么人们倾向于避免使用复合主键而倾向于使用代理键和唯一约束的原因之一。

下面是一个有效的示例(使用Oracle,但它在所有RDBMS版本上都是一样的)。首先,我们创建一个具有单列主键的父表,并从子表引用它。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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一个复合主键,事情就会分崩离析……

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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> 

我们需要向子表添加匹配的第二列,并将其包含在外键定义中:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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>
票数 1
EN

Stack Overflow用户

发布于 2010-08-24 12:52:30

只能将选定的列或所有列的组合用作外键。

票数 1
EN

Stack Overflow用户

发布于 2010-08-24 15:20:14

简而言之,一个表的主键在其他表中用作外键。我们不使用一个表的所有列作为其他表中的外键(这将再次导致冗余,这也是有问题的)。

此外,您还可以在其他表中使用主键唯一键、主键+‘某些其他列’等作为外键。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3556685

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文