如何限制每个记录的前导密钥数量

时间:2019-07-10 22:26:47

标签: sql foreign-keys constraints

我有3个表Title,Detail,TypeDetail,并且需要添加外键或规则,约束等。如何控制每个Title的Details数量,它只能包含每种类型的Detail。

我尝试使用外键。

我的桌子

Create table Title(
TitleID int identity(1,1) primary Key not null)

Create table Type(
TypeID int identity(1,1) primary Key not null)

Create table Detail(
DetailID int identity(1,1) primary Key not null,
TitleID int REFERENCES Title(TitleID),
TypeID int REFERENCES Type(TypeID))

标题中的数据

TitleID
1
2

数据类型

TypeID
1
2
3

详细数据

DetailID|TitleID|TypeID
1|1|1
2|1|2
3|1|3
4|2|1
5|2|2
6|1|1 // cant because I all ready inserted the Type 1 for Title 1

我想限制自己。 mo帮助?

1 个答案:

答案 0 :(得分:1)

我认为您想要一个独特的约束条件

create table Detail (
    DetailID int identity(1,1) primary Key not null,
    TitleID int REFERENCES Title (TitleID),
    TypeID int REFERENCES Type (TypeID),
    constraint unq_detail_title_type unique (Title, Type)
);

这将不允许表中有重复的对。