【问题标题】:Database (de)normalization - table with images for different entities数据库(反)规范化 - 包含不同实体图像的表
【发布时间】:2013-02-09 22:42:58
【问题描述】:

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

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)

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

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

image_batches 有额外的列image_type_id。将有image_type 用于productsuserseverything else that needs images。而不是product_identry_id 哪个image_type products 将是产品ID,对于图像类型users 将是user_id 等等。

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

你有什么建议?

【问题讨论】:

    标签: mysql database normalization denormalization


    【解决方案1】:

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

    长答案:你想做的事情的名称是“多态关联”。有几种方法可以解决这个问题:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-10-10
      • 1970-01-01
      • 2013-12-27
      • 2017-08-21
      • 2016-06-06
      • 2015-02-15
      • 2019-04-02
      • 1970-01-01
      相关资源
      最近更新 更多