【问题标题】:Composite primary key and foreign key relationship复合主键和外键关系
【发布时间】:2016-06-02 19:57:56
【问题描述】:

我需要各位专家的设计建议

所以我有如下表格:

表 1

( A integer not null
, B char(1) not null
, C integer not null
, D not null
, primary key (A, B, C) i.e. composite key
)

表 2

( A integer not null
, B char(2) not null
, C integer not null
primary key (A, B,C) composite key
)

表 3

( A integer not null
, B char(2) not null
 , D not null
primary key (A, B, D)
)

我想在表 1 和 2 和表 1 和 3 之间建立关系。

表 1 是父表,表 2 和 3 是表 1 的子表。我可以轻松地在表 1 和表 2 之间创建关系,但是当我尝试在 1 和 3 之间创建关系时出现错误,因为外部key 不能是组合键的一部分,它必须是整个组合键。我非常感谢任何建议。

【问题讨论】:

  • 嗯...根据外键的定义,您不能只使用主键的一部分。以您的示例为例,假设您想使用 A 作为外键。但是 Table1 中有 10 行具有该值。外键属于哪一行???这没有逻辑意义。或许如果您能用某种含义而不是 Table1 来解释您的情况,ColA 我们可以提供帮助。
  • 缺少一些列类型 - 该 DDL 是否真的运行?
  • 如果在表 1 中为列 A、B、D 添加一个UNIQUE 索引,那么这三个列可以用作表 3 的外键...如果这三个在T1 那么它们不构成表中的,因此它们不能是不同表中的外键。

标签: sql sql-server sql-server-2008


【解决方案1】:

这就是你要找的吗?

create table table1 (
    A int not null ,
    B char(1) not null ,
    D int not null ,
    constraint pkTable1 primary key clustered ( A , B , D )
    )
create table table2 (
    A int not null ,
    B char(1) not null ,
    C int not null ,
    constraint pkTable2 primary key clustered ( A , B , C ) ,
    constraint fkABC@table2 foreign key ( A , B , C ) references table1 ( A , B , D )
    )
create table table3 (
    A int not null ,
    B char(1) not null ,
    D int not null ,
    constraint fkABC@table3 foreign key ( A , B , D ) references table1 ( A , B , D )
    )

注意foreign key ( A , B , *D* ) 部分。根据问题的措辞,不确定您是否在 table2 上使用主键,但无论如何它是存在的。

综上所述,如果table2 从属table1,我的倾向是:

create table table1 (
    t1ID int identity(1,1) not null ,
    constraint uni_t1ID@table1 unique nonclustered ( t1ID ) ,
    A int not null ,
    B char(1) not null ,
    C int not null ,
    constraint pkTable1 primary key clustered ( A , B , C )
    )
create table table2 (
    t2ID int identity(1,1) not null ,
    constraint uci_t2id@table2 unique nonclustered ( t2id ) ,
    t1ID int not null ,
    constraint fk_t1ID@table2 foreign key ( t1ID ) references table1 ( t1ID )
    )
create table table3 (
    t3ID int identity(1,1) not null ,
    constraint uci_t3id@table3 unique nonclustered ( t3id ) ,
    t1ID int not null ,
    constraint fk_t1ID@table3 foreign key ( t1ID ) references table1 ( t1ID )
    )

根据偏好(有些人更喜欢无意义的主键,有些人更喜欢对人类有一定意义的主键),您可以用主键替换身份字段上的唯一索引,并确保放置(A,B,C) 上的唯一索引,以确保数据完整性。

【讨论】:

  • 我的问题让你感到困惑吗?因为你完全忽略了 D 列
  • 嗯,也许确实如此 - 您是否注意到我在其中包含 D 列作为关系的一部分?否则,我想我错过了你的问题 - 你能澄清一下吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2020-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多