这是两个表:
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
值。这是另一个奇怪的事情 - 并非全部
但其中一些
显示是
,而应该是否
。谢谢!
最佳答案
试试这个:
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
用户关注者
1,2,10
1,3,11
2,3,10
3,1,13
并得到了预期的结果:
2,b,bcde,1,否
3,c,cdef,1,是
关于用于查找关注者和关注的 Mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53609175/