Home  >  Q&A  >  body text

SQL query to get users who are both followed by someone and follow that person

I have a scenario where I want to find users who are following user X and user X is following them.

View the following architecture: Database table with test values

We have follower_id and following_id, Now let's say we want to check if the user with id 23 is following someone and they are also following him.

As you can see, user 22 is following user 23, So we want to get the details of user 22 like name and email from user table.

User 23 follows 24, but user 24 does not follow user 23, so we will not include user 24 in the list.

Please help me write the query to get the list of users for the above scenario. Thanks

renew

Because I need more information about the user. I'm currently implementing a slow solution in Laravel.

$UsersIAmFollowing = UserFollowing::where('follower_id', $user->id)->get();
        $UsersFollowingMe = UserFollowing::where('following_id', $user->id)->get();
        $friends = [];
        foreach ($UsersIAmFollowing as $userIamFollowing) {
            foreach ($UsersFollowingMe as $userFollowingMe) {
                if($userIamFollowing->following_id == $userFollowingMe->follower_id){
                    array_push($friends, User::find($userIamFollowing->following_id));
                }
            }
        }

        dd($friends);

P粉562845941P粉562845941203 days ago299

reply all(1)I'll reply

  • P粉356128676

    P粉3561286762024-03-30 15:18:57

    select t.id 
          ,t.follower_id    
          ,t.following_id
    from   t join t t2 on t2.following_id = t.follower_id 
             and          t.following_id = t2.follower_id
    id follow_id Below_id
    7 twenty two twenty three
    6 twenty three twenty two

    reply
    0
  • Cancelreply