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

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

在评论中,您说过一件物品总是与其员工属于同一个客户,但并非所有物品都属于一名员工。

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

我要避免的是将 ClientID 作为 Item 上的非空外键关系 - 这会重复 "an item without an explicit client ID inherits the client ID from its employee" 的逻辑。它没有表现力(阅读模式的人无法弄清楚),并且会引发错误。

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

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

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

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

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

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

这避免了 Item 上的属性重复,但表现力较差,因为它使用了一种更常用于多对多关系的模式,并且没有显式声明 "either or".