【问题标题】:How to design tables with a higher level of nesting?如何设计嵌套层次更高的表格?
【发布时间】:2016-09-21 09:54:05
【问题描述】:
我正在使用 C# 制作一个在线电影数据库作为学校项目。目前我正在研究数据库模型。在我的电影数据库中,您可以评论新闻文章、电影和评论本身。正如您在下面的图片链接中看到的那样,我设计了一个评论表,如果它是对评论的评论,它可以有 Article_ID 或 Movie_ID 或没有。这是一个好习惯吗?
http://s17.postimg.org/dg6wnp6jz/comment_table.png
我的直觉说不。创建更多表不是更好吗?一个给电影-cmets,一个给新闻-cmets,一个给cmets上的cmets?还是为它制作连接表更好?
处理这种更高级别的嵌套有什么好的做法? [想想对评论的评论,评论本身也有评论]
提前致谢。
【问题讨论】:
标签:
c#
sql
database
database-design
relational-database
【解决方案1】:
您可以使用带有父引用的模型树结构,例如:
电影帖子
id | movie_id | post_text | date_of_post | post_author
----------- -------- -------------------- ------------ -----------
post_movie1 | movie1 | the post about movie | today | one author
movie-posts-cmets
id | movie_post_id | parent_comment_id | comment_text | datetime_of_comment | commenter
----- --------------- | ---------------- ----------------------------------- | ------------------- | ----------------
comm1 | post_movie1 | null | first comment about movie1 | today 10:10:01 | user one
comm2 | post_movie1 | null | second comment about movie1 | today 10:50:01 | user two
comm3 | post_movie1 | comm2 | first commet about comm2 of movie1 | today 11:10:10 | user one
comm4 | post_movie1 | null | another comment about movie1 | today 12:15:00 | other user
comm5 | post_movie1 | comm2 | second comment about comm2 movie1 | today 16:50:01 | user two
您将在同一张表中获得所有评论。通过日期时间可以轻松识别新旧cmets,通过父关系字段可以识别cmet之间的de关系
这种结构是嵌套模型结构的一个很好的替代方案;您将有更少的阅读工作(单个表 - 单个查询)并且您的写入事务将是原子的。
【解决方案2】:
解决方案的适当性可能取决于开发框架。
如果这是 Ruby on Rails,我会说你所拥有的是一种多态关系,其中评论表将包含“commentable_type”和“commentable_id”列。 commentable_type 将包含关联表(或模型,在 Rails 术语中)的名称,例如“Movie”、“Article”、“Comment”等,commentable_id 将包含其主键。
这通常意味着您不能使用数据库外键约束,而必须依赖应用程序强制的完整性。