繁体   English   中英

数据库设计:循环引用以及如何更正

[英]Database Design: Circular reference and how to correct it

数据库设计:一个项目与客户和员工有关。员工与客户有关

这是循环引用吗? 如果是这样,我该如何改进我的模型?

您没有任何循环引用。 我解释数据模型说:

An Item belongs to exactly 1 Client
An Item belongs to 0 or 1 Employee
An Employee belongs to exactly 1 Client

循环引用会将An Employees to exactly 1 Item添加An Employees to exactly 1 Item

在评论中,您说某个项目始终与其员工属于同一客户,但并非所有项目都属于员工。

有几种方法可以对此进行建模。

我会避免将 ClientID 作为 Item 上的非空外键关系 - 这重复了“没有显式客户端 ID 的项目从其员工那里继承客户端 ID”的逻辑。 它没有表现力(阅读模式的人无法弄清楚),并且会带来错误。

一种选择是使item->employeeitem-> client的基数都是可选的(即 0..1)。 你的约定是if an item has a client relationship, it may not have an employee relationshipif an item has an employee relationship, it may not have an explicit client relationship; the client is determined by the employee. if an item has an employee relationship, it may not have an explicit client relationship; the client is determined by the employee. 您无法在您的架构中清楚地表达这一点,并且必须将其构建到您的数据访问代码中。

另一种选择是创建两种类型的项目,一种具有 clientID 外部关系,另一种具有 employeeId 外部关系。 从模式的角度来看,这更具表现力 - 大概有一些业务概念可以用来命名表。 但是,如果Item有很多属性,那么您就重复了很多。

最后,您可以将项目与客户或员工的关系存储在单独的联接表中:

Item
-------
ItemID
...

ItemEmployees
-----------------
ItemID
EmployeeID

ItemClients
----------
ItemID
ClientID

这避免了 Item 上的属性重复,但表达能力较差,因为它使用了更常用于多对多关系的模式,并且没有明确声明“非此即彼”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM