外键是否总是指主键?
Does a foreign key always refer to a primary key?
我对此有点困惑。外键必须始终引用主键吗?如果同一个 table 上有两个外键引用同一个主键怎么办?
谢谢
包含一个外键的一组列 table 必须引用具有主键或唯一键约束的 table 中的一组等效列。
您当然可以在同一个 table 中有 2 个或更多 FK,它们指的是同一个 PK 或 UK。这模拟了一种关系,其中 child 记录与多个 parent 记录相关 - 例如代表生物学 child 的记录可能对他们父亲和母亲的记录有 FK。
请注意,唯一索引不足以达到此目的;需要唯一约束,否则您将得到 "ORA-02270: no matching unique or primary key for this column-list".
"What if there's two foreign key on the same table that refer to the same primary key?
"
任意数量的 child table 可以引用 parent table。在某些情况下,child table 可能在同一个 parent 上有多个外键。
例如,任何形式的体育比赛都有相同类型的对手 - 球员、球队等。因此一场比赛将有该实体的两个实例,因此 child table 将有两个外键引用相同主键的列。
create table player (
player_id number not null primary key
, name varchar2(30) not null unique
);
create table match (
match_id number not null primary key
, player_1 number not null
, player_2 number not null
, match_played date not null
, result varchar2(10)
, constraint match_player1_fk foreign key (player_1) references player
, constraint match_player2_fk foreign key (player_2) references player
);
外键可以引用唯一约束而不是主键。然而,这不是标准做法。使用唯一键来强制执行候选键 - 业务键 - 并且这些并不总是 suitable 用作外键是惯例。
例如在我的示例中,PLAYER.NAME
是一个唯一的键:每个玩家都必须有一个不同的名字。但是,使用 NAME
作为 MATCH
上的外键是不合适的,因为人们可以更改他们的名字。使用合成主键 PLAYER_ID
更方便,因为它不会在 PLAYER
记录的生命周期内改变。
我对此有点困惑。外键必须始终引用主键吗?如果同一个 table 上有两个外键引用同一个主键怎么办?
谢谢
包含一个外键的一组列 table 必须引用具有主键或唯一键约束的 table 中的一组等效列。
您当然可以在同一个 table 中有 2 个或更多 FK,它们指的是同一个 PK 或 UK。这模拟了一种关系,其中 child 记录与多个 parent 记录相关 - 例如代表生物学 child 的记录可能对他们父亲和母亲的记录有 FK。
请注意,唯一索引不足以达到此目的;需要唯一约束,否则您将得到 "ORA-02270: no matching unique or primary key for this column-list".
"What if there's two foreign key on the same table that refer to the same primary key? "
任意数量的 child table 可以引用 parent table。在某些情况下,child table 可能在同一个 parent 上有多个外键。
例如,任何形式的体育比赛都有相同类型的对手 - 球员、球队等。因此一场比赛将有该实体的两个实例,因此 child table 将有两个外键引用相同主键的列。
create table player (
player_id number not null primary key
, name varchar2(30) not null unique
);
create table match (
match_id number not null primary key
, player_1 number not null
, player_2 number not null
, match_played date not null
, result varchar2(10)
, constraint match_player1_fk foreign key (player_1) references player
, constraint match_player2_fk foreign key (player_2) references player
);
外键可以引用唯一约束而不是主键。然而,这不是标准做法。使用唯一键来强制执行候选键 - 业务键 - 并且这些并不总是 suitable 用作外键是惯例。
例如在我的示例中,PLAYER.NAME
是一个唯一的键:每个玩家都必须有一个不同的名字。但是,使用 NAME
作为 MATCH
上的外键是不合适的,因为人们可以更改他们的名字。使用合成主键 PLAYER_ID
更方便,因为它不会在 PLAYER
记录的生命周期内改变。