在关注者和关注者关系表上获取Mutual Friends

时间:2017-11-18 11:43:25

标签: php mysql sql

如何获得共同的朋友SQL查询?

我的Sql

但我不能得到共同的朋友

enter image description here

id | user_id
--------------
1   |  2
2   |  3
3   |  4
4   |  1

Relation Table 

id  | follower_id | following_id
--------------------------------
1   | 1          | 2
2   | 2          | 1
3   | 1          | 4
4   | 4          | 3
5   | 4          | 1

查询后

"SELECT `user_id` FROM " . T_USERS . " WHERE `user_id` IN (SELECT `following_id` FROM " . T_FOLLOWERS . " WHERE `follower_id` = {$user_id} AND `following_id` <> {$user_id} AND `active` = '1') AND `active` = '1' ";

关注者查询

" SELECT `user_id` FROM " . T_USERS . " WHERE `user_id` IN (SELECT `follower_id` FROM " . T_FOLLOWERS . " WHERE `follower_id` <> {$user_id} AND `following_id` = {$user_id} AND `active` = '1') AND `active` = '1'";

1 个答案:

答案 0 :(得分:0)

SELECT `user_id` FROM " . T_USERS . "
 WHERE `user_id` IN (SELECT CASE WHEN `following_id`={$user_id} THEN `follower_id` ELSE `following_id` END user
                       FROM " . T_FOLLOWERS . "
                      WHERE `active` = '1'
                        AND ((`follower_id` = {$user_id} AND `following_id` <> {$user_id})
                          OR (`follower_id` <> {$user_id} AND `following_id` = {$user_id}))
                      GROUP BY user
                     HAVING count(*)=2
                    )
   AND `active` = '1'