首页 > 解决方案 > 如何创建一个 ISA 层次结构,其中 SQL 中只允许存在一种子类型?

问题描述

例如,我有一张 Person 表格。该表如下所示:

create table Person (id int not null primary key, 
FirstName varchar(20) not null,
LastName varchar(20) not null
)

ISA Hierarchy 有 2 个扩展类型,Staff 和 Student,在它下面如下:

create table Staff (
id int not null primary key references Person(id),
department varchar(20) not null
)
create table Student (
id int not null primary key references Person(id),
course varchar(20) not null
)

从当前的实现中,我可能会创建一个 Student 条目和 Staff 条目,它们都与同一个 Person ID 相关。我试图使其具有排他性,以便一个人只能成为员工或学生,但我对如何做到这一点有点迷茫。

任何输入表示赞赏!

标签: sqlprimary-keyhierarchy

解决方案


在现实世界中,某人可能既是工作人员又是学生,但您所描述的情况是某人可能只是其中之一。因此,“员工或学生”类别是个人的单值属性,因此该类别值应存储在Person表中。为了约束子表,表应该在两个和那个类别列Person上都有一个额外的唯一索引,然后你的和表也应该包括这个列,并在外键中使用它返回到,并有一个检查约束来确保只有适当的值(因此,人的类别)被输入到每个子表中。idStaffStudentPerson


推荐阅读