Create a SQL table that can have cascading child parent relationships

喜夏-厌秋 提交于 2020-03-05 00:27:37

问题


I have a set of entities that can have child entities which themselves have child entities and they have child entities .... etc. The problem is that the number of subsequent child entities is not constant between entities.

Example:

Car has an engine, the engine have multiple components which may comprise multiple parts and the parts my have smaller parts

As stated above, the number of subsequent child entities cascading down is different for instance between a Train and a Car, so I cannot create indefinite child tables for each parent.

My question is, what is the most efficient way to store such data and maintain a relationship between each parent and subsequent child? An example will be much appreciated.


回答1:


The simplest data model would be a tree like this:

TABLE Entity (Id, Name, EntityTypeId, ParentEntityId NULL)
TABLE EntityType (Id, Name, ParentEntityTypeId NULL)

In a more complex model, e.g. different car models sharing the same motor model (and it's not clear whether you are talking about car models, or specific cars), the ParentEntityId column would be replaced by a relation table:

TABLE Entity (Id, Name, EntityTypeId)
TABLE EntityHierarchy (Id, ParentEntityId, ChildEntityId)

The entries in the EntityHierarchy table would be constrained (on application level) by the tree of EntityTypes

In a more complex model, the ParentEntityTypeId would also be replaced by a hierarchy table.

If your entities or their types change over time, you would also add a DATE range to any of these tables.



来源:https://stackoverflow.com/questions/60174974/create-a-sql-table-that-can-have-cascading-child-parent-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!