MySQL Table 结构:每个项目的多个属性

MySQL Table structure: Multiple attributes for each item

我想问你哪种方法是创建具有以下情况的 MySQL 数据库结构的最佳方法。

我有一个 table 和 items,不需要描述,因为这里唯一重要的字段是 ID

现在,我希望能够为每个项目分配一些属性 - 当然是 ID。但我不知道具体该怎么做,因为我想保持动态(因此,如果我想添加新的属性类型,我不必修改 table 结构)。

我的想法

我认为 - 事实上,我现在拥有的结构 - 我可以使用以下结构制作 table items_attributes

+----+---------+----------------+-----------------+
| id | item_id | attribute_name | attribute_value |
+----+---------+----------------+-----------------+
|  1 |       1 | place          | Barcelona       |
|  2 |       2 | author_name    | Matt            |
|  3 |       1 | author_name    | Kate            |
|  4 |       1 | pages          | 200             |
|  5 |       1 | author_name    | John            |
+----+---------+----------------+-----------------+

我以数据为例,大家看看那些属性是可以重复的(不是1对1的关系)。

这种方法的问题

我需要做一些查询,其中一些是为了统计目的,如果我有很多项目的很多属性,这可能会有点慢。

此外 - 可能是因为我不是 MySQL 方面的专家 - 每次我想进行搜索并找到 "those items that have 'place' = 'Barcelona' AND 'author_name' = 'John'" 时,我最终不得不进行多个 JOINs对于每个条件。

重复之前的例子,我的查询最终会像这样:

SELECT * 
FROM items its 
JOIN items_attributes attr 
   ON its.id = attr.item_id 
      AND attr.attribute_name = 'place' 
      AND attr.attribute_value = 'Barcelona' 
      AND attr.attribute_name = 'author_name' 
      AND attr.attribute_value = 'John';

如您所见,这将 return 什么都没有,因为 attribute_name 不能在同一行中同时有两个值,而 OR 条件不会是我想要的我正在搜索,因为项目必须具有所述的两个属性值。

所以唯一的可能性是对每个要搜索的条件在相同的重复table上做一个JOIN,我认为当有很多术语要搜索时执行起来很慢为.

我想要什么

正如我所说,我希望能够保持属性类型动态,因此通过在 'attribute_name' 上添加新输入就足够了,而不必向 [= 添加新列65=]。此外,由于它们是 1-N 关系,因此不能将它们作为新列放入 'items' table。

如果您认为该结构是唯一可以实现我的兴趣的结构,如果您可以点亮一些想法,使搜索查询不是一大堆 JOIN,那就太好了,也是。

不知道是不是很难弄到手,一直绞尽脑汁到现在也没有想出办法。希望你们能帮助我!

无论如何,感谢您的时间和关注!

亲切的问候。

您的思考方向是正确的,normalization. The normal for you would like to have in your database is the fifth normal form (or sixth, even). Whosebug on this matter 的方向。

Table 属性:

+----+----------------+
| id | attribute_name | 
+----+----------------+
|  1 |          place |
|  2 |    author name |
|  3 |          pages |
+----+----------------+

Table ItemAttribute

+--------+----------------+
| item_id|   attribute_id | 
+--------+----------------+
|      1 |              1 |
|      2 |              1 |
|      3 |              2 |
+--------+----------------+

因此,对于对象(在本例中为项目)的每个 属性,您创建一个新的 table 并相应地命名。它需要大量连接,但您的数据库将非常灵活和有条理。祝你好运!

在我看来应该是这样的,我知道有很多 table,但实际上它规范了你的数据库 也许这就是为什么,因为我不能理解你从哪里得到你的 att_value 专栏,以及什么应该包含这个专栏