java - 将朋友列表实现到数据库中的最佳方法?MySQL
问题描述
所以我的项目有一个“朋友列表”,在 MySQL 数据库中我创建了一个表:
名字A
姓名B
主键(nameA,nameB)
这将导致很多条目,但为了确保我的数据库是规范化的,我不确定如何实现这一点?
我的项目也使用 Redis .. 我可以将它们存储在那里。
当一个人加入服务器时,我必须搜索所有条目以查看他们的名字是nameA还是nameB,然后将这两个名字放在一起作为朋友,这也可能效率低下。
干杯。
解决方案
The task is quite common. You want to store pairs where A|B has the same meaning as 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:
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. 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, i.e. you could have friendships of three four or more users.
No method is really much better than the other.
推荐阅读
- maven - 使用 maven liquibase 比较相同数据库模式的两种状态
- php - 条件为真时退出三元运算符
- machine-learning - 如何使用信息增益 (IG) 编码朴素贝叶斯
- c - 如何在 Linux 子系统中的 VSCode 上运行程序集 (.s) 文件
- asp.net - ASP.NET Webforms Repeater 在按钮单击/回发时无法正确加载自定义控件
- pandas - 如果值是多个,熊猫将值放在一个组中
- c# - C#通过反射获取属性值没有默认值
- python - 字符串中的索引列表引用
- c++ - 如何使用 memset 填充数组的最大值?
- ldap - LDAP 查询以检查用户是否是特定安全组的成员