主鍵 | 關注者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"