使用连接进行 MySQL 关注者查询

标签 mysql sql join

我有两个表:关注者:

  followee_id | followers_id
--------------|--------------
       1      |      2
       1      |      3
       2      |      3
       3      |      1

和用户:

| user_id | user_name | etc... 
|---------|-----------|-------
|    1    |   user1   |
|    2    |   user2   |
|    3    |   user3   |

以及一个按关注者数量排序的前 50 位用户的查询:

SELECT followers.followee_id AS user_id, COUNT(*) followers, users.user_name, users.user_profile_picture, users.display_name
FROM followers
INNER JOIN users
ON users.user_id = followers.followee_id
GROUP BY followee_id ORDER BY followers DESC LIMIT 50 

以及一个选择您是否关注它们的查询:

SELECT followers.followee_id, 1 AS follows_them FROM followers WHERE followers_id = 1

我需要加入他们,以便我有一个表(用户 3)显示:

| user_id | user_name | followers | follows_them | follow_you | etc...
----------|-----------|-----------|--------------|------------|-----------
     1    |   user1   |      2    |       1      |      1     |
     2    |   user2   |      1    |       1      |      2     |
     3    |   user3   |      1    |       0      |      0     |

其中表格按用户拥有的关注者数量排序

SQLFiddle: http://sqlfiddle.com/#!9/17815

最佳答案

SqlFiddleDemo

请仔细检查,我的主要语言不是英语,所以不确定谁关注谁。

SELECT 
      T.*,
      if(f_to.followee_id is null, 'no', 'yes') is_followby_userid,
      if(f_him.followee_id is null, 'no', 'yes') is_following_userid      
FROM 
    (
      SELECT followers.followee_id AS user_id,
          COUNT(*) followers,
          users.user_name,
          users.user_profile_picture,
          users.display_name
      FROM followers
      INNER JOIN users
          ON users.user_id = followers.followee_id
      GROUP BY followee_id
      ORDER BY followers DESC LIMIT 50
    ) T
LEFT JOIN followers f_to
       ON T.user_id = f_to.followee_id
      and f_to.followers_id = 1    -- your @user_id
LEFT JOIN followers f_him       
       ON T.user_id = f_him.followers_id
      and f_him.followee_id = 1    -- your @user_id

输出

| user_id | followers | user_name | user_profile_picture | display_name | is_followby_userid | is_following_userid |
|---------|-----------|-----------|----------------------|--------------|--------------------|---------------------|
|       1 |         2 |     User1 |       1_562a7cb9.jpg |     User One |                 no |                  no |
|       2 |         1 |     User2 |       2_562b7cb9.jpg |     User Two |                 no |                 yes |
|       3 |         1 |     User3 |       3_562c7cb9.jpg |   User Three |                yes |                 yes |

关于使用连接进行 MySQL 关注者查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33572361/

相关文章:

mysql - 使用 AWS s3 版本控制存储 gzip 压缩的 mysql 转储是否更有效?

php - 根据变量获取自定义表格

php - 帮助逻辑

mysql - 计算每个产品每天有多少个条形码

php - 良好运行系统的备份

使用特殊字符时MySQL更新错误

sql - 具有行版本控制的 PostgreSQL 数据库

MySQL查询计算特定日期范围内的用户保留率

mysql - 不能将左连接与联合结合

arrays - $lookup 两层