主键 | 关注者id | 被关注者id |
1 | 1 | 2 |
2 | 1 | 3 |
3 | 2 | 1 |
4 | 2 | 3 |
5 | 3 | 1 |
6 | 3 | 4 |
7 | 4 | 3 |
8 | 5 | 6 |
9 | 7 | 8 |
先建一张好友关系表
CREATE TABLE IF NOT EXISTS `follower` ( `id` int(6) unsigned NOT NULL, `user_id` varchar(200) NOT NULL, `follower_id` varchar(200) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8; INSERT INTO `follower` (`id`, `user_id`, `follower_id`) VALUES ('1', '1', '2'), ('2', '1', '3'), ('3', '2', '1'), ('4', '2', '3'), ('5', '3', '1'), ('6', '3', '4'), ('7', '4', '3'), ('8', '5', '6'), ('9', '7', '8');
我关注的人
select * from follower where user_id = '1'
关注我的人
select * from follower where follower_id = '1'
跟我互关的人
select a.user_id from follower as a inner join follower as b on a.follower_id = '1' and b.follower_id = '1'
但是运行上方代码,会有重复数据出现;
跟我互关的人去重
select a.* from ( select a.user_id from follower as a inner join follower as b on a.follower_id = '1' and b.follower_id = '1' ) a group by a.user_id;
判断两人关系(互关)
select 1 from follower where user_id = '1' and follower_id = '2' union all select 2 from follower where user_id = '2' and follower_id = '1'
这里会返回一个List<Integer> 数组,有四种情况
- 空数组 A,B 之前无任何关系
- [1,2] "1" 和 "2"相互关注
- [1] "1" 关注了 "2"
- [2] "2" 关注了 "1"