我正在考虑使用一个 image
表来存储任何其他独立表的图像,例如 user
、product
等... (当然,独立表的任何单个实例(例如作为用户
的John Smith
,以及作为产品
的笔记本电脑
) ) 可能有 0 个、1 个或多个图像
。
image
表包含 id
、title
和 filename
。
我正在考虑使用一个 imagetable
表将图像
与其正确的图像所有者
(例如用户
)相关联> 包含以下字段:image_id
、table_id
和 table
。
某些条目可能如下所示:
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_image
、product_image
和 company_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/