首页 > 解决方案 > 超类型和子类型以及一对一的关系

问题描述

我在 SQL Server 超类型中有以下超类型/多个子类型表:医生和子类型:儿科医生、骨科和牙医

    create table Doctor
(
    DoctorID int primary key,
    Name varchar(100),
    -- add some other common attributes (all of vendor, sponsor, volunteer have) here.
)

create table Paediatrician
(
    PaediatricianId int primary key,
    DoctorID int foreign key references Doctor(DoctorID)
    -- add some other attributes related to Paediatrician here.
)

create table Orthopedic
(
    OrthopedicId int primary key,
    DoctorID int foreign key references Doctor(DoctorID)
    -- add some other attributes related to Orthopedic here.
)

create table Dentist
(
    DentistId int primary key,
    DoctorID int foreign key references Doctor(DoctorID)
    -- add some other attributes related to Dentisthere.
)

我的业务逻辑是医生可以是儿科医生、牙医或骨科医生。不能超过一种子类型。基于上述设计,这不是强制的。我可以创建 Id = 1 的 Doctor,然后转到 Dentist 和 Orthopedictables 并在两个表中分配 DoctorId 值 1。我如何强制执行,以便医生只能出现在一张桌子上?

标签: sqlsql-serverdatabase-design

解决方案


我会以不同的方式安排这一点。我将有 3 个表,一个 Doctor 表(就像你已经拥有的),一个 Specialist 表和一个 SpecialistAttributes 表。

医生表包含所有医生的信息,很简单。

专家表包含您的专家类型 ID 和专家描述等。您的 3 位示例专家将在此表中各占一行。

SpecialistAttributes 表包含专家所需的所有属性。在您的 Doctor 表中,您有一个外键来查找 SpecialistTypeID,因此只能有 1 个,然后 SpecialistType 有许多可以链接到的 SpecislaistAttibutes。

以这种方式组织数据的另一个好处是您需要添加任何专家角色或属性,您不需要更改数据库的结构,只需添加更多行。

Doctor Table
    | ID | Name     | Specialist_FK |
    ---------------------------------
    | 1  | Smith    | 2             |
    | 2  | Davies   | 3             |
    | 3  | Jones    | 3             |

Specialist Table
    | ID | Speciality    |
    ----------------------
    | 1  | Paediatrician |
    | 2  | Orthopedic    |
    | 3  | Dentist       |

SpecialistAttribute Table
    | ID | SpecialityID+FK | Description          | Other      |
    ------------------------------------------------------------
    | 1  | 1               | Paediatrician Info 1 | Other Info |
    | 2  | 1               | Paediatrician Info 2 | Other Info |
    | 3  | 2               | Orthopedic Info 1    | Other Info |
    | 4  | 2               | Orthopedic Info 1    | Other Info |
    | 5  | 3               | Dentist Info 1       | Other Info |
    | 6  | 4               | Dentist Info 1       | Other Info |

推荐阅读