【问题标题】:How to create an ISA Hierarchy where only one subtype is allowed to exist in SQL?如何创建一个 ISA 层次结构,其中 SQL 中只允许存在一种子类型?
【发布时间】:2021-12-15 04:36:45
【问题描述】:

例如,我有一张 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 相关。我试图使其具有排他性,以便一个人只能成为员工或学生,但我对如何做到这一点有点迷茫。

感谢任何输入!

【问题讨论】:

  • 实现此目的的一种方法是通过在员工和学生表上插入触发器之前。并让这些触发器检查 Person 表中的标志字段是否已为 ID 填写。 F.e.一个名为“类型”的字段。还可以使用更新 Persons 中的标志字段的 AFTER INSERT 触发器。

标签: sql primary-key hierarchy


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多