如何设计一个具有多2多关系的数据库
我已经很长时间没有设计数据库了,只是想确保我设计得正确。
我有一个具有名称和描述的实体。
该实体可以有许多实体类型的子实体。
所以它就像一个递归关系。现在确定如何正确设计数据库。
我要创建第二个表还是什么?
更新:一个实体只能有一个父实体或没有父实体。
It's been a long time since I designed a database and just want to make sure that I am designing it properly.
I have an Entity which has a name and description.
This Entity can have many subEntities which are of type Entity.
So its like a recursive relationship. Now sure how to design the db properly.
Do I create a second table or what?
Update: One entity can only have a single parent entity or no parents.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编辑:根据问题的更新,我建议的解决方案以粗体显示,如下:
首先,让我们明确这是否真的是多对多的情况,因为从您的描述中不清楚是否不管是真是假。
您描述了一个树结构,其中实体可以具有“嵌套”实体,并且大概这些嵌套实体可以各自拥有自己的嵌套实体。但这只是一个多对多问题,如果一个实体可以同时属于多个父实体。
无论哪种情况,您都将把所有实体存储在一个表中。 如果您想表示没有多重父子关系的“简单”嵌套实体树,则可以将
parent_entity_id
列添加到entities
表中,该列指向 <父级的 code>entity_id。顶级实体在此列中将具有标志值(例如 -1)或NULL
。 在这种情况下,您只需要多一列,并且不需要新表来表示的关系。如果它确实是具有多个父子关系的多对多关系,那么您将创建一个新表
entity_links
,其中包含列parent_entity_id
和child_entity_id
。您可以通过在此表中插入和删除行来管理关系。Edit: Based on the update to the question, my suggested solution is in bold, below:
First, let's be clear whether this is really a many-to-many situation because it's not clear from your description whether that's true or not.
You describe a tree structure in which an entity can have "nested" entities and, presumably, those nested entities can each have their own nested entities. But this is only a many-to-many question if a single entity can belong, simultaneously to multiple parents.
In either case, you will store all the entities in a single table. If you want to represent a "simple" tree of nested entities without multiple-parentage then you can add a
parent_entity_id
column to theentities
table which points to theentity_id
of the parent. Top level entities would have either a flag value (for instance, -1) or aNULL
in this column. In this case, you need only one more column and no new tables to represent the relationship.If it's really a many-to-many relationship with multiple-parentage then you will create a new table
entity_links
with columnsparent_entity_id
andchild_entity_id
. You manage the relationships by inserting and deleting rows in this table.在关系数据库中,您将使用连接表,故事结束。
我无法与核心数据交谈。
In a relational database, you'd use a join table, end of story.
I can't speak to Core Data.
对于关系数据库:
您的实体不应该有一个子实体,它是另一个实体(或者数据库不会采用正常形式),它可以包含关系(取决于您的需要,一对一,一对多,多对-许多)到同一个表/实体。
For relational databases:
Your entity should not have a sub-entity which is another entity (or the db wont be in normal form) it can contain a relationship (depending on your needs either one-to-one, one-to-many, many-to-many) to the same table/entity.
对于多对多关系,您需要一个交集表来委托其自身之间的关系
例如,
For a Many-to-Many relationship you'll want an intersection table to delegate the relationships between itself
For Example,