mysql - 数据库(反)规范化 - 包含不同实体图像的表

标签 mysql database normalization denormalization

我有一个数据库架构,用于存储产品图像元数据,如下所示:

image_sizes (this is purely metadata - what sizes to create of given image, eg "thumb", "main image", "sidebar widget icon of the product", etc):
image_size_id (auto-increment, pk)
name (thumb, main)
max_width
max_height
crop (flag, to crop or just resize to fit)

images table:
image_id (auto-increment, pk)
image_size_id (fk to image_sizes)
image_batch_id (fk to batches, when there is uploaded image for the product, an image is created for each product size, all the images have same batch_id, described below)
location (relative path to the project eg uploads/products/thumbs)
width (result after processing, in pixels
height (result after processing, in pixels)
size (in bytes)

image_batches tables:
image_batch_id (auto-increment, pk)
product_id (fk, to which product it belongs)
original_filename (eg the file was called 123.jpg when uploaded)
is_default (if the product 10 images, one is default)

因此,这个架构允许我获取产品的所有“缩略图”并显示它们。现在的问题是,我希望应用程序中的用户或其他实体(也可以说还有 field )拥有相同的架构。

如果我修改以下架构是否合适,以便:

image_batches 有附加列 image_type_id产品用户所有其他需要图像的东西都会有image_type。并且将 product_id 改为 entry_id,对于 image_type products 将是产品 ID,对于图像类型 users 将是 user_id 等等。

我知道这是非规范化,可能会导致问题(如果应用程序端存在错误)。但如果我需要新类型实体的图像来创建一组 3 个新表来处理相同的问题,那么开销似乎太大了。这样,应用程序端也会出现(某种)代码重复。

你有什么建议?

最佳答案

简短的回答:不,那将使用数据库反模式 - 主要问题是缺乏引用完整性,因为您无法在该表上定义外键。

长答案:你想要做的事情的名称是“多态关联”。有几种方法可以实现:

解决方案 A) 有两个可为空的列:product_id 和 user_id

这比仅仅拥有一个entry_id更好,因为您可以定义外键。您的应用程序只需确保 image_batches 表中的每一行中的一列(且只有一列)为 NULL。

解决方案 B) 有两个中间表:product_image_batches 和 user_image_batches,每个表都引用您的 image_id

这将减轻维护应用程序完整性的负担,并将其移至数据库,但会引入两个新表。

关于mysql - 数据库(反)规范化 - 包含不同实体图像的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15055955/

相关文章:

java - 在表中插入一行而不提交所需的外键

mysql - 重命名mysql数据库而不需要持久转储?

c++ - 是否有一个函数可以检索范围内可用的不同值的数量?

mysql - 如何在 MySQL 中获取多个插入行的 ID?

python - 如何在 Storm 拓扑中将结果写入 MySQL?

MySql 删除 - 与选择(加入)相同

MySql 部分求和

database - PostgreSQL 中数据类型 "Numeric"可以支持负数吗?

mysql - 错误代码 : 1052 Column 'admin_id' in field list is ambiguous

python - tf-idf : should I do normalization of documents length