[英]storing several ID's from another table in one column?
Apologies if this is really stupid but I don't have any experience in php and mysql to know how things should be done. 抱歉,如果这确实很愚蠢,但我对php和mysql没有任何经验,不知道应该怎么做。 I have a customer table in a mysql db and a group table:
我在mysql数据库和组表中有一个客户表:
customers - ID name email phone group groups - ID name description 客户-ID名称电子邮件电话组群组-ID名称描述
So I need to assign groups to customers if necessary, this can be more than one group to each customer. 因此,如有必要,我需要为客户分配组,每个客户可以有多个组。 So eg customer 1 is in group 4,5,6
因此,例如客户1在组4,5,6中
What way should I assign groups in the group column of the customer table. 我应该以什么方式在客户表的组列中分配组。 Should I just add the group ID's separated by commas, then just use explode when I need to get the individual ID's out?
我应该只添加用逗号分隔的组ID,还是在需要取出单个ID时使用explode?
Maybe this isn't the right approach at all, could someone enlighten me please. 也许这根本不是正确的方法,请有人启发我。 I would appreciate knowing the right way to do this, thanks.
感谢您知道正确的方法,谢谢。
Do not store multiple IDs in one column. 不要在一个列中存储多个ID。 This is a denormalization that will make it much harder to query and change your data, as well as hurting performance.
这是一种非规范化,这将使查询和更改数据变得更加困难,并且会损害性能。
Instead, create a separate CustomerGroup
table (with CustomerID
and GroupID
columns), and have one row per Customer/Group relationship. 而是,创建一个单独的
CustomerGroup
表(具有CustomerID
和GroupID
列),并且每个Customer / Group关系具有一行。
Should I just add the group ID's separated by commas, then just use explode when I need to get the individual ID's out?
我应该只添加用逗号分隔的组ID,还是在需要取出单个ID时使用explode?
No! 没有! If you do that then you won't quickly be able to (for example) query for which users there are in a specific group.
如果这样做,您将无法快速(例如)查询特定组中的哪些用户。
Instead use a join table with two columns, each of which has a foriegn key constraint to the corresponding table. 而是使用一个连接表有两列,每个有foriegn键约束对应的表。
group_id customer_id
4 1
5 1
6 1
Here is an example of tables to show how you should implement this : 这是一个表格示例,说明如何实现此目的:
Table 1 CONSUMERS: 表1消费者:
id name email
1 john john@something.com
2 ray ray@something.com
Table 2 GROUPS : 表2组:
id group_name description
1 music good music group
2 programming programmers
Table 3 CONSUMERS_GROUPS 表3 CONSUMERS_GROUPS
consumer_id group_id
1 1
1 2
2 1
Now the table 3 is listing consumers ids which belong to which group id. 现在,表3列出了属于哪个组ID的消费者ID。
This type of relationship is called one to many relation where, one consumer can have many groups. 这种关系称为一对多关系,其中一个消费者可以有许多组。 Reverse might also be true where one group can have many consumers.
在一组可以有许多消费者的地方,反向也可能是正确的。 In that case relationship is called many to many
在这种情况下,关系称为多对多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.