用于查找关注者和关注的 Mysql 查询

标签 mysql sql

这是两个表:

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

我知道我已经很接近了;)。问题是,即使用户没有跟进,我也会得到 followingyes 值。这是另一个奇怪的事情 - 并非全部其中一些显示,而应该是。谢谢!

最佳答案

试试这个:

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/

相关文章:

PHP:按 DESC 排序不行吗?

mysql - MySql 中的固定行数

c# - ASP.net/c# SQL 代码通过文本框提交

python - 如何进行 Django 子查询

mysql - 如何将一个列中的所有值与另一个表中的列相乘?

mysql - SQL:连接一个有限制的列?

mysql - 如何在 codeigniter 中编写 3 where_in() 的查询

mysql - 在具有联接表的查询中,如何设置仅影响一行而不影响联接创建的所有行的 where 子句

mysql - 在 php 上创建表时出现 sql 语法错误

MySQL 联合对 select 语句进行单独排序而不是组合