问题描述
假设您有一个实体列表:帖子、问题和图库,这些实体可以被用户喜欢和评论,也可以持有标签。
压缩事物以便没有一堆表格是一个好主意吗(选项 1),或者最好创建尽可能多的表格,尽管这些表格看起来非常类似于彼此(选项 2)。
选项 1
- 创建一个通用的like_、评论和标签 TABLE,其中包含“entity_type”,以便您知道喜欢属于哪个实体以及实体 TABLE以确保数据完整性。这个选项的一个好处是我可以添加更多实体,并且每个实体只需创建 1 个表,而每个实体只需要创建 4 个表(一个用于实体、一个类似连接表、一个注释连接表、一个标签连接表):
实体
- entity_id 主键
entity_type
- en_type 文本主键
- 说明
发布
- post_id 主键
- post_id REFERENCES entity(entity_id);
画廊
问题
- question_id 主键
- question_id REFERENCES entity(entity_id)
喜欢_
- entity_type
- entity_id
- user_id
- entity_type REFERENCES entity_type(en_type)
- entity_id REFERENCES entity(entity_id);
- entity_type
- entity_id
- user_id
- 通讯
- entity_type REFERENCES entity_type(en_type)
- entity_id REFERENCES entity(entity_id);
tag_to_entity
- entity_type
- entity_id
- tag_id
选项 2
- 分离一切。这里的一切都很简单,但有更多的桌子。
发布
- post_id 主键
画廊
- gallery_id 主键
问题
- question_id 主键
like_to_post
- post_id
- user_id
- post_id REFERENCES post(post_id)
like_to_gallery
like_to_gallery
- question_id
- user_id
- question_id REFERENCES 问题(question_id)
comment_to_post
- post_id
- user_id
- comment_text
- post_id REFERENCES post(post_id)
comment_to_gallery
comment_to_question
- question_id
- user_id
- comment_text
- gallery_id REFERENCES 问题(question_id)
tag_to_post
- post_id
- tag_id
- post_id REFERENCES post(post_id)
tag_to_gallery
tag_to_question
- question_id
- tag_id
- question_id REFERENCES 问题(question_id)
解决方法
我会说选项 2 更可取,因为:
- 它允许数据库对您连接的表强制执行外键约束
- 性能可能会更好,因为连接的大小会小得多