[英]Best way to implement friends list into a database? MySQL
So my project has a "friends list" and in the MySQL database I have created a table:所以我的项目有一个“朋友列表”,在 MySQL 数据库中我创建了一个表:
nameA姓名A
nameB姓名B
Primary Key (nameA, nameB)主键(名称A,名称B)
This will lead to a lot of entries, but to ensure that my database is normalised I'm not sure how else to achieve this?这将导致大量条目,但为了确保我的数据库规范化,我不知道如何实现这一目标?
My project also uses Redis.. I could store them there.我的项目也使用 Redis。我可以将它们存储在那里。
When a person joins the server, I would then have to search for all of the entries to see if their name is nameA or nameB, and then put those two names together as friends, this may also be inefficient.当一个人加入服务器时,我必须搜索所有条目,看看他们的名字是nameA还是nameB,然后将这两个名字放在一起作为朋友,这也可能效率低下。
Cheers.干杯。
The task is quite common.任务很普通。 You want to store pairs where A|B has the same meaning as B|A.
您想存储 A|B 与 B|A 具有相同含义的对。 As a table has columns, one of the two will be stored in the first column and the other in the second, but who to store first and who second and why?
由于表有列,两者中的一个将存储在第一列中,另一个存储在第二列中,但是谁先存储谁第二个,为什么?
One solution is to always store the lesser ID first and the greater ID second:一种解决方案是始终首先存储较小的 ID,然后存储较大的 ID:
userid1 | userid2 --------+-------- 1 | 2 2 | 5 2 | 6 4 | 5
This has the advantage that you store each pair only once, as feels natural, but has the disadvantage that you must look up a person in both coumns and find their friend sometimes in the first and sometimes in the second column.这样做的好处是您每对只存储一次,感觉很自然,但缺点是您必须在两个 couns 中查找一个人,有时在第一列中找到他们的朋友,有时在第二列中找到他的朋友。 That may make queries kind of clumsy.
这可能会使查询变得笨拙。
Another method is to store the pairs redundantly (by using a trigger typically):另一种方法是冗余存储对(通常使用触发器):
userid1 | userid2 --------+-------- 1 | 2 2 | 1 2 | 5 2 | 6 4 | 5 5 | 2 5 | 4 6 | 2
Here querying is easier: Look the person up in one column and find their friends in the other.在这里查询更容易:在一个列中查找此人并在另一列中找到他们的朋友。 However, it looks kind of weird to have all pairs duplicated.
但是,将所有对都复制看起来有点奇怪。 And you rely on a trigger, which some people don't like.
而且你依赖于一些人不喜欢的触发器。
A third method is to store numbered friendships:第三种方法是存储编号的友谊:
friendship | user_id -----------+-------- 1 | 1 1 | 2 2 | 2 2 | 5 3 | 2 3 | 6 4 | 4 4 | 5
This gives both users in the pair equal value.这为配对中的两个用户提供了相等的价值。 But in order to find friends, you need to passes: find the friendships for a user, find the friends in these friendships.
但是为了找到朋友,你需要通过:为用户找到朋友,在这些朋友中找到朋友。 However, the design is very clear and even extensible, ie you could have friendships of three four or more users.
但是,设计非常清晰,甚至可以扩展,即您可以拥有三个四个或更多用户的友谊。
No method is really much better than the other.没有一种方法确实比另一种好得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.