DB Design for Choosing One of Multiple Possible Foreign Tables

丶灬走出姿态 提交于 2019-12-31 02:34:06

问题


Say if I have two or more vastly different objects that are each represented by a table in the DB. Call these Article, Book, and so on. Now say I want to add a commentening feature to each of these objects. The comments will behave exactly the same in each object, so ideally I would like to represent them in one table.

However, I don't know a good way to do this. The ways I know how to do this are:

  • Create a comment table per object. So have Article_comments, Book_comments, and so on. Each will have a foreign key column to the appropriate object.
  • Create one global comment table. Have a comment_type that references "Book" or "Article". Have a foreign key column per object that is nullable, and use the comment_type to determine which foreign key to use.

Either of the above ways will require a model/db update every time a new object is added. Is there a better way?


回答1:


There is one other strategy: inherit1 different kinds of "commentable" objects from one common table then connect comments to that table:

All 3 strategies are valid and have their pros and cons:

  1. Separate comment tables are clean but require repetition in DML and possibly client code. Also, it's impossible to enforce a common key on them, unless you employ some form of inheritance, which begs the question: why not go straight for (3) in the first place?
  2. One comment table with multiple FKs will have a lot of NULLs (which may or may not be a problem storage and cache-wise) and requires adding a new column to the comments table whenever a new kind of "commentable" object is added to the database. BTW, you don't necessarily need the comment_type - it can be inferred from what field is non-NULL.
  3. Inheritance is not directly supported by current relational DBMSes, which brings its own set of engineering tradeoffs. On the up side, it could enable easy addition of new kinds of commentable objects without changing the rest of the model.

1 Aka. category, subclassing, generalization hierarchy... For more on inheritance, take a look at "Subtype Relationships" section of ERwin Methods Guide.




回答2:


I personally think your first option is best, but I'll throw this option in for style points:

Comments have a natural structure to them. You have a first comment, maybe comments about a comment. It's a tree of comments really.

What if you added one field to each object that points to the root of the comment tree. Then you can say, "Retrieve the comment tree for article 123.", and you could take the root and then construct the tree based off the one comment table.

Note: I still like option 1 best. =)



来源:https://stackoverflow.com/questions/14408992/db-design-for-choosing-one-of-multiple-possible-foreign-tables

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