通用表/连接表是个好主意吗?

问题描述

假设您有一个实体列表:帖子、问题和图库,这些实体可以被用户喜欢和评论,也可以持有标签

压缩事物以便没有一堆表格是一个好主意吗(选项 1),或者最好创建尽可能多的表格,尽管这些表格看起来非常类似于彼此(选项 2)。

选项 1

  • 创建一个通用的like_评论标签 TABLE,其中包含“entity_type”,以便您知道喜欢属于哪个实体以及实体 TABLE以确保数据完整性。这个选项的一个好处是我可以添加更多实体,并且每个实体只需创建 1 个表,而每个实体只需要创建 4 个表(一个用于实体、一个类似连接表、一个注释连接表、一个标签连接表):

实体

  • entity_id 主键

entity_type

  • en_type 文本主键
  • 说明

发布

  • post_id 主键
  • post_id REFERENCES entity(entity_id);

画廊

  • gallery_id 主键
  • gallery_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

  • gallery_id
  • user_id
  • gallery_id 参考画廊(gallery_id)

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

  • gallery_id
  • user_id
  • comment_text
  • gallery_id 参考画廊(gallery_id)

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

  • gallery_id
  • tag_id
  • gallery_id 参考画廊(gallery_id)

tag_to_question

  • question_id
  • tag_id
  • question_id REFERENCES 问题(question_id)

解决方法

我会说选项 2 更可取,因为:

  1. 它允许数据库对您连接的表强制执行外键约束
  2. 性能可能会更好,因为连接的大小会小得多

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...