复合主键和外键关系

时间:2016-06-02 19:57:57

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

我需要所有专家的设计建议

所以我有如下表格:

表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不能是复合键的一部分,它必须是整个复合键。我非常感谢任何建议。

1 个答案:

答案 0 :(得分:0)

这有点像你在找什么?

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)的唯一索引,以确保数据的完整性。