mysql - 是否建议将(图像)表与(用户)、(产品)、(公司)以及任何独立的表相关联?

标签 mysql database database-design relational-database database-schema

我正在考虑使用一个 image 表来存储任何其他独立表的图像,例如 userproduct 等... (当然,独立表的任何单个实例(例如作为用户John Smith,以及作为产品笔记本电脑) ) 可能有 0 个、1 个或多个图像

image 表包含 idtitlefilename

我正在考虑使用一个 imagetable 表将图像与其正确的图像所有者(例如用户)相关联> 包含以下字段:image_idtable_idtable

某些条目可能如下所示:

image_id | table_id | table
-----------------------------
1        | 1        | user
2        | 1        | user

3        | 2        | user
4        | 2        | user

5        | 1        | product
6        | 1        | product
7        | 1        | product

8        | 2        | product

9        | 3        | product
10       | 3        | product

11       | 4        | product

现在的问题是:

是否建议采用这种数据库设计?满足此请求的最佳方法是什么?

当然,另一种方法是使用 user_imageproduct_imagecompany_image 表,而不是单个 image_table表。

最佳答案

不,因为这样你就失去了外键的优势。

使用联结表:

create table product (
  product_id bigserial primary key,
  name citext not null unique
);

create table user (
  user_id bigserial primary key,
  name citext not null unique
);

-- personally, I would store the file in the db and use incremental backups
-- pedantically, I prefer "picture" over "image" as "image" has 2 meanings in computers
create table picture (
  picture_id bigserial primary key,
  filename citext not null,
  ...
);

create table product_picture (
  product_id bigint references product(product_id),
  picture_id bigint references picture(picture_id),
  primary key (product_id, picture_id)
);

create table user_picture (
  user_id bigint references user(user_id),
  picture_id bigint references picture(picture_id),
  primary key (user_id, picture_id)
);

关于mysql - 是否建议将(图像)表与(用户)、(产品)、(公司)以及任何独立的表相关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17876523/

相关文章:

database - 拆分 Access 数据库而不能创建唯一的 fe

sql - 需要建议以根据审计表重新创建表的历史记录

java - Hibernate/JPA,每个关联实体的列上的唯一约束(例如 : each user cannot have duplicate entries but can be duplicates overall)

mysql - 铁路查询系统开发,Trains、Stations、Stops如何建模?

mysql - ALTER TABLE 添加复合主键

mysql - 外键引用值仅使用一次

mysql - 从表中获取值并将其传递到 url 中

php - 如何设置实时数据源来更新轮胎价格和库存?

database - 使用阿姆斯特朗公理计算规范覆盖

mysql - SQL数据库-为另一表列获取一列最大值