我正在考虑使用一个image表来存储任何其他独立表(如userproduct等)的图像(当然,独立表的任何单个实例(例如John Smith作为,并且user作为laptop)可以具有0、1或多个product

image表具有imageidtitle

而且我正在考虑使用filename表将imagetable与其适当的image(如image owner)与以下字段相关:userimage_idtable_id

一些条目可能如下所示:

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


现在的问题是:

是否建议使用此数据库设计?对此请求最好的方法是什么?

当然,另一种方法是具有tableuser_imageproduct_image表,而不是单个company_image表。

最佳答案

不,因为那样您会失去外键的优势。

使用联结表:

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/

10-12 21:46