简体   繁体   English

在mysql列中存储列表

[英]Storing list in mysql column

Each row on my mysql table represents a different item. 我的mysql表上的每一行代表一个不同的项目。 Each item has a attribute used_by_classes which can be a list with more than one element and up to 9, such as "Scout,Spy,Pyro" 每个项目都有一个used_by_classes属性,该属性可以是包含多个元素且最多9个元素的列表,例如"Scout,Spy,Pyro"

I wonder what is the overall best way to store that information. 我想知道什么是存储该信息的最佳方法。

I was storing it as a list like above on a table used_by_classes and exploding it with php. 我将其存储为如上表中的used_by_classes并用php进行used_by_classes

$classes= explode(",", $used_by_classes);

But thats just unreliable and probably silly. 但这就是不可靠的,可能很愚蠢。 Creating 9 separate columns is another alternative but complicates things further on. 创建9个单独的列是另一种选择,但会使事情进一步复杂化。 How would you deal with this ? 您将如何处理?

For multi-valued attributes, the normative pattern is to create a second table. 对于多值属性,规范模式是创建第二个表。 Each row in the new table will store one value of the attribute. 新表中的每一行将存储该属性的一个值。

If the first table is 如果第一个表是

item (id int unsigned primary key, ...)

The second table would be something like: 第二张表如下所示:

item_class
( id            INT UNSIGNED PRIMARY KEY
, item_id       INT UNSIGNED NOT NULL COMMENT 'FK ref item.id'
, used_by_class VARCHAR(20)  NOT NULL

We'd likely add a unique constraint on the (item_id, used_by_class) tuple. 我们可能会在(item_id, used_by_class)元组上添加唯一约束。 With InnoDB, we'd create a FOREIGN KEY constraint referencing the item table. 使用InnoDB,我们将创建引用项目表的FOREIGN KEY约束。

item
 id name 
--- -----
 11 Cake

item_class
 id item_id used_by_class
--- ------- ------------- 
412      11 Scout
413      11 Spy
414      11 Pyro
415      11 Demoman

I think you can also serialize that data at store them. 我认为您也可以在存储它们时序列化该数据。 and when when you fetch the record you can un-serialize them all. 当您获取记录时,您可以全部取消序列化。

item
id  name   used_by_class
--- ----- ---------------
11  Cake   {scout:Spy:pyro}

similar like this 像这样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM