大家好,
Let's say I have 4 tables named "user", "office", "product", "event". And another table named "document". A same document can be assigned to one or many users, offices, products and events. So here we need a many-to-many relationship. But I have 3 ways to do that :
-a table named "user_document", another named "office_document", "product_document" and "event_document" which all have a field named "document_id" which is foreign key for document id and another field "user_id" (for user_document) which is foreign key to user id (and so on with office, product and event of course...)
OR
-a table named "document_ownership" which has these fields : "document_id", "user_id", "office_id", "product_id" and "event_id". Here document_id should be not Null and one (or more) of other fields that can be Null. For example if I set a same document for a user and a product, I will have a row with document_id, user_id and product_id not Null.
OR
-a table named "document_ownership" that will have these fields : "document_id", "relation_type" and "relation_id". Here relation_type field is for example a string (which represent the relation table name) or a foreign key pointing to another additionnal table named for example "relationtype" in which we have strings like "user" (id=1), "office" (id=2), "product" (id=3) and "event" (id=4) (which also represent the relation table name), and relation_id which is the id of the specified relation table (relation_type)
我的问题是,这 3 种方式做我想做的事情的优点/缺点是什么?最好的做法是什么?
预先感谢您的建议,
米哈尔
最佳答案
这个问题并不能真正回答。纯粹主义者会说方法 1 是正确的,但它并不总是那么简单。可以这样想 - 您的数据库设计应该表达数据之间的关系以及数据的含义。因此,您的每种方法都暗示了有关数据性质的几件事。
方法 1 表示用户、办公室、产品和事件都很重要,哦,是的,他们可以拥有文档。也许吧。
方法 2 表示文档很重要,我们需要跟踪每个文档的相关内容。所以文档是关键,其他所有内容都围绕它进行注释。
方法 3 更加复杂和技术性更强,并且并没有真正给出您希望如何使用数据的想法。
在所有情况下数据都是相同的。它只是设计数据来讲述应该如何使用它的故事。
抱歉,太抒情了。只是我的 0.02 美元。
关于mysql - SQL多对多关系3种方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39225009/