Here are the two tables:
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
Find follower of user: 2 Output should be:
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
I need a mysql query to find all the followers of a particular user with detail information of the followers from user table and need to know the number of followers each follower has and i also need to if the the particular user also following the follower. Here’s what I have tried:
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
I know I’m getting close ;). The problem is, I’m getting following with a yes value even though the user is not following back.Here is another weird thing – not all but some of them showing yes which should be no .Thanks!
Advertisement
Answer
Try this:
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
I tried it using the following data sets:
USER
1,a,abcd
2,b,bcde
3,c,cdef
user_follower
1,2,10
1,3,11
2,3,10
3,1,13
And got the expected result:
2,b,bcde,1,no
3,c,cdef,1,yes