在社交类系统中,用户与用户的好友关系的设计必不可少,那么如何设计好友的数据库至关重要,本篇文章带大家学习一下相关的设计方案。

基础分析

第一步,有一张用户表,表内包含用户的基本信息,比如账号、姓名、性别等信息。这里用tb_user表示用户信息表。

ID 用户名
1 张三
2 李四
3 王五
4 赵六
第二步,需要将用户与用户直接建立好友关系。这里有两种情况:单向好友关系、互为好友关系。
- 单向好友关系就是张三在李四的好友列表中,但李四没有在张三的好友列表中;
- 互为好友关系,如果张三和李四为好友,则双方都在彼此的好友列表中;

好友关系设计

无论上面两种关系的哪一种,好友关系表都可以使用下面的设计,表tb_friend:

ID user_id friend_id
1 1 2
2 1 3
示例中,张三拥有李四和王五两个好友。

单向好友模式

如果是单向好友模式,那么两个人互为好友关系则插入的数据应该是这样:

ID user_id friend_id
1 1 2
2 2 1
也就是张三是李四的好友,李四也是张三的好友。此时使用sql语句查询时只用限定user_id作为条件即可查询出用户的好友列表:
select * from tb_friend where user_id = 1
互为好友关系

因为是互为好友关系,则只需要插入一条数据即可。对应的查询语句为:
select * from tb_friend where user_id = 1 or friend_id = 1
当然也可以使用UNION ALL来实现:
select friend_id as friends from tb_friend where user_id = 1 UNION ALL --使用
UNION ALL,因为不存在重复的 select user_id as friends from tb_friend where friend_id = 1
注意事项:
- user_id1–>friend_id2和user_id2–>friend_id1是相同的记录,不需要重复插入;
- 为了快速判断两个人是不是好友,可在程序层插入数据前添加一个限制user_id1 < user_id2;
- 可加入缓存层(Redis或Memcached)来提高性能;
- 可从数据库层限制(user_id,friend_id)不可重复;

加入分组

如果好友数量比较多,关系比较复杂,可引入好友分组,可进行如下改造:

ID user_id friend_id user_group friend_group
1 1 2 好友 同学
2 1 3 同学 同学
在数据库中添加了user_group,当前user给friend设置的分组,friend_group是当前user的朋友对其设置的分组类别。

于是,查询好友列表的SQL如下:
select friend_id as friends ,user_group as my_group from tb_friends where
user_id =1 UNION ALL select user_id as friends , friend_group as my_group from
friend_id =1
小结


至此社交系统中好友关系的设计及SQL语句使用基本完成。可根据具体的业务情况进行修改。在查询除好友的id列表之后就可以进行好友信息的查询。此处需要注意的是如果用in语句来查询会有不走索引、sql语句大小限制、性能等问题,可考虑使用左连接进行查询。

原文链接:https://www.choupangxia.com/topic/detail/74
<https://www.choupangxia.com/topic/detail/74>

关注微信公众

更多技术、架构、管理等知识分享,请关注微信公众号:程序新视界(ID:ershixiong_see_world)

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信