Skip to content
Advertisement

MySQL query to find values in table with given value and find others that are similar

I have a table called followers and I want to be able to find the current users followers, display that list, and then compare those values against another user ID to see if they are following them or not from that same table

This is the table I’m using currently to get the list of followers for a specific user:

followers
-------
followId         - primary key, the unique id for the follow relationship
userId           - the user that is following someone
orgId            - that someone that the user is following

I tried using a union query but I wouldn’t want to due to performance reasons (table may contain high volume of records) and because it isn’t scalable (I think)?

The expected output should be the list of orgId’s for which the user(the user I am checking against) is following, and another column that shows whether my user(my userId that I provide) is following that orgId value (i.e a following column).

Advertisement

Answer

Hmmm, if I understand correctly, you have two users and you want to know which orgs followed by the first are also followed by the second:

select f.orgid,
       (exists (select 1
                from followers f2
                where f2.userId = $seconduserid and
                      f2.orgid = f.orgid
               )
       ) as seconduserflag
from followers f
where f.userId = $firstuserid
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement