我应该如何将列表存储在数据库中
我应该如何在网络应用程序中保存整数列表?
我正在设计一个类似 facebook 的应用程序,对于每个用户,我需要保存他朋友的 id,因此考虑到用户凸轮甚至有 1000 个朋友和数据库字段,我认为数据库中的 csv 没有被指示应包含此列表的字段是固定的,csv 可能会溢出该字段。
我应该将这些列表存储在本地服务器文件中还是数据库仍然是最佳选择?
How should I save a list of int(s) in a web app ?
I am designing a facebook-like app and for every user I need to save the ids of his friends, so a csv in the DB I don't think is indicated taking into account that a user cam even have 1000 friends and the database field that should contain this list is fixed, the csv may overflow that field.
Should I store these lists in local server files or is the database still the best option?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
多对多关系通常使用单独的表来处理。
然后,您可以使用 JOIN 找出谁是给定用户的朋友
Many-to-many relationships are typically handled using a separate table.
You then use a JOIN to find out who is friends with a given user
您正在寻找的是一个连接表,将用户连接到自身。该表中的条目代表一个用户与另一个用户之间的友谊。
Users 表
Friends 表
UserID 和 FriendID 都是 Users 表的外键。您可能希望对 (UserID,FriendID) 对有唯一性约束,并对 UserID 有非唯一索引。请注意,UserID 是 Users 表的 PK,ID 是 Friends 表的 PK。对好友表使用单独的 PK 可以更轻松地在界面中引用特定的用户/用户对。
What you are looking for is a join table, joining Users to itself. An entry in this table would represent a friendship between one user and another.
Users table
Friends table
Both UserID and FriendID would be foreign keys to the Users table. You'd probably want to have a uniqueness constraint on the pair (UserID,FriendID) and a non-unique index on UserID. Note that UserID is the PK for the Users table and ID is the PK for the Friends table. Using a separate PK for the Friends table will make it easier to refer to a particular user/user pair in your interfaces.
您不应该将列表存储在数据库的单个字段中 - 您将无法轻松查询它。多值列几乎总是错误的选择。
在数据库设计方面,您应该有一个多对多表来连接用户和朋友(您可能还希望在表中存储相应的相反关系,以便于双向关系的遍历)。
You shouldn't store a list in a single field of the database - you will not be able to easily query it. Multi-valued columns are almost always the wrong choice.
In terms of database design, you should have a many-to-many table to connect users to friends (you may want to also store the corresponding opposite relationship in your table, for easy traversal of the bi-directional relationship).
使用数据库。
今天你可能有 1000 个朋友。
明天,10000。显然,仅使用 CSV 无法很好地扩展。
Use a database.
Today you might have 1000 friends.
Tomorrow, 10000. Obviously, this won't scale very well using only CSV.