这是两个表:
1.user
user_id | full_name | username
1 A A_1
2 B B_2
3 C C_3
4 D D_4
5 E E_5
2.user_follower
user_id | follower_id | follow_dtm
2 4 2018-10-09 10:10:10
2 3 2018-01-09 11:10:10
1 5 2018-11-09 07:10:10
4 2 2018-10-09 06:10:10
4 5 2018-10-09 00:10:10
查找用户的关注者:2
输出应为:
user_id: 4 fullname: D username: D_4 f_total_flwr: 2 (num of flwr of id-4) following: yes
user_id: 3 fullname: C username: C_3 f_total_flwr: 0 (num of flwr of id-3) following: no
我需要一个mysql查询来找到特定用户的所有关注者,并具有
user
表中关注者的详细信息,并且需要知道每个关注者具有的关注者数量,并且我还需要特定用户是否也关注该关注者。这是我尝试过的:SELECT u.user_id
, u.full_name
, u.username
, COUNT(DISTINCT uf.follower_id) f_total_flwr
, case when b.user_id is null then 'no' else 'yes' end following
FROM user_follower
JOIN user u
ON user_follower.follower_id = u.user_id
LEFT
JOIN user_follower uf
ON u.user_id = uf.user_id
LEFT
JOIN user_follower b
ON b.user_id = user_follower.follower_id
and b.user_id = u.user_id
WHERE user_follower.user_id=2
GROUP
BY u.user_id
ORDER
BY uf.follow_dtm DESC
LIMIT 30
我知道我要靠近了;)。问题是,即使用户没有跟进,我仍在使用
following
值获取yes
这是另一个奇怪的东西-not all
但some of them
显示yes
应该是no
。谢谢! 最佳答案
尝试这个:
select u2.*,b.fcount, case when uf3.user_id is null then 'no' else 'yes' end as connected from user u2 inner join
(
select u.user_id,count(distinct(uf2.follower_id)) fcount
from user u
inner join user_follower uf1 on u.user_id=uf1.follower_id and uf1.user_id=1
left join user_follower uf2 on uf2.user_id=uf1.follower_id
group by u.user_id
) b on u2.user_id=b.user_id
left join user_follower uf3 on u2.user_id=uf3.user_id and uf3.follower_id=1
我使用以下数据集进行了尝试:
用户
1,a,abcd
2,b,bcde
3,c,cdef
user_follower
1,2,10
1,3,11
2,3,10
3,1,13
并得到了预期的结果:
2,b,bcde,1,no
3,c,cdef,1,是
关于mysql - MySQL查询查找关注者并关注,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53609175/