首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >形成循环引用的表

问形成循环引用的表
EN

Stack Overflow用户
提问于 2014-03-12 15:51:00
回答 2查看 139关注 0票数 0

我正在为学校管理系统设计一个数据库。数据库将保存多个学校的数据。我正在设计的表格正在形成圆形reference..It,看起来像这样:

学校- SchoolId (Pk),SchoolName,RegistrationNo,.....

部门- DeptId (Pk),SchoolId(Fk),DeptName,...

教师- TeacherId (Pk),DeptId (Fk),SchoolId(Fk),姓名,....

学校将有不同的部门和教师。教师将属于特定的部门。

如何避免此循环引用..

如有任何帮助/建议,我们将不胜感激。谢谢

EN

回答 2

Stack Overflow用户

发布于 2014-03-12 15:53:43

您应该删除引用SchoolId的教师上的FK,因为给定一位教师,您可以通过FK to the Department表访问他的学校。

然而,正如Unbeliever所说,这不是循环引用,只是规范化错误。

票数 1
EN

Stack Overflow用户

发布于 2014-03-12 16:03:23

好的,所以(根据你的评论)我们有一个情况,并不是所有的老师都属于部门。有两种方法可以对此进行建模。

第一个是使Teacher中的SchoolId和DeptId都可以为空,并有一个检查约束来确保这些列中只有一列不为空。因此,一个没有部门的教师有一个SchoolId,而一个部门的教师只有一个DeptId。

代码语言:javascript
复制
CREATE TABLE Teacher (
    TeacherID float not null primary key,
    DeptId float null,
    SchoolId float null,
    constraint CK_Teacher_School_or_Dept CHECK (
         (DeptId is null and SchoolId is not null) or
         (DeptId is not null and SchoolId is null)
    ),
    constraint FK_Teacher_School FOREIGN KEY (SchoolID)
          references School (SchoolID),
    constraint FK_Teacher_Dept FOREIGN KEY (DeptId)
          references Department (DeptId)
)

处理这个问题的第二种方法是在Department中为DeptId和SchoolId添加一个唯一键约束,然后在从Teacher到Department的这两列上都应用一个外键。当DeptId为null时,不会检查这个外键约束,因此一切正常。当DeptId不为null时,它用于强制Teacher中的SchoolId列与部门中的SchoolId匹配。

代码语言:javascript
复制
CREATE TABLE Department (
    DeptId float not null primary key,
    SchoolId float not null,
    constraint FK_Department_Schools FOREIGN KEY (SchoolId)
          references School (SchoolID),
    constraint UQ_Departement_WithSchool UNIQUE (DeptId,SchoolID)
)

CREATE TABLE Teacher (
    TeacherID float not null primary key,
    DeptId float null,
    SchoolId float not null,
    constraint FK_Teacher_School FOREIGN KEY (SchoolID)
          references School (SchoolID),
    constraint FK_Teacher_Dept FOREIGN KEY (DeptId,SchoolID)
          references Department (DeptId,SchoolID)
    /* Optional - still have the FK on just DeptID if you think it
       better documents the "real" relationship */
)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22345121

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档