MySQL 存储值列表(例如兴趣)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7766322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Store list of values (such as interests)
提问by Dan
I've got a table of Users (ID, FNAME, LNAME, INTERESTS,...) plus another table to hold the specific set of INTERESTS they can choose from: Film, TV, Radio, Stage, Standup.
我有一张用户表(ID、FNAME、LNAME、INTERESTS...)和另一个表来保存他们可以选择的特定兴趣集:电影、电视、广播、舞台、站立。
They can have more than one interest, so how can I store this information in the Users INTERESTS's field? Or what is the best alternative method to achieve this?
他们可以有多个兴趣,那么我如何将这些信息存储在用户兴趣的字段中?或者实现这一目标的最佳替代方法是什么?
回答by Neville Kuyt
It's a many-to-many relationship. You store these by intoducing a "join table".
这是一个多对多的关系。您可以通过引入“连接表”来存储这些。
Table Users:
-----------
UserID PK
Name
...
Table Interests
-------
InterestID PK
Description.
....
User_interest
-----------
UserID PK, FK
InterestID PK, FK
回答by Lightness Races in Orbit
Read about database normalisationin your MySQL book. It's an important topic, so there's probably a large chapter about it.
在您的 MySQL 书中阅读有关数据库规范化的信息。这是一个重要的话题,所以可能有一章是关于它的。
In short, you remove interests
and end up instead with a thirdtable, like:
简而言之,您删除interests
并最终得到第三个表,例如:
user_id | interest_id
--------+------------
1 | 1
1 | 2
2 | 1
3 | 4
This gives you your many-to-many relationship.
这为您提供了多对多关系。
回答by oezi
the best solution to this is to use 3 tables (a third one for storing the connection of interests to useres):
对此的最佳解决方案是使用 3 个表(第三个表用于存储兴趣与用户的联系):
user (id, name)
interest (id, description)
user_interest (user, interest)
this is called database normalization.
这称为数据库规范化。