Skip to content
Advertisement

Query to check relationships between columns?

I currently have a table called User_Followers this table has the following columns:

User_Id Follower_Id

I’m trying to build a query that will retrieve all the people a user is following but no being followed back by.

For example:

User ID | Follower ID

1              2
1              4
3              1
4              2
4              3

In the example above, if I was to check for users not following back User 4. It should return 1.

Similarly if I was to check for users not following back User 2, it should return 1 and 4

Advertisement

Answer

I’m trying to build a query that will retrieve all the people a user is following but no being followed back by.

If I understand correctly, then not exists seems to do what you want:

select uf.user_id
from User_Followers uf
where uf.follower_id = @user and
      not exists (select 1
                  from User_Followers uf2
                  where uf2.user_id = uf.follower_id and
                        uf2.follower_id = uf.user_id
                 );
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement