jeudi 26 février 2015

SQL social connections query


Given the following 2 tables:



Profiles
---------
id, name

Connections
-----------
id1, id2, status


where status is (for the sake of the example) either 'pending', or 'active'.


What I'm trying to do is to select all the profiles that match a certain name (for the example I'll ignore any pattern matching) excluding the id of the profile that is doing the searching.


The part I am having trouble with is that for each profile in the result set, I want its connection status relative to the id of the profile doing the searching. In other words, if profile 99 is searching, then all search results who have id1 in the Connections table = 99 will show the status equal to that row in the connection table. If there is no row in the Connection table, it should show null.


(I am actually storing Connections bi-directionally, e.g. if 1 is connected to 2, then there are 2 rows (1,2) and (2,1) - this is why I only need to check id1 for instance)


Sample:



Profiles
--------
1, 'Joe'
2, 'Jane'
3, 'Fred'

Connections
-----------
1, 2, 'active'
2, 1, 'active'
(e.g. Joe is Connected to Jane)

Expected results (profileId, name, status):
If Joe searches for 'Fred': 3, 'Fred', null
If Joe searches for 'Jane': 2, 'Jane', 'active'
If Fred searches for 'Jane': 2, 'Jane', null


Basically what this query should do is give a person all profiles matching a name query (excluding their own) with the status the searcher's connection to each profile in the result.


What I tried:



select profile.id, profile.name, connection.status from Profiles as profile
left join Connections as connection (on connection.id1 = profile.id)
where profile.id <> {id_of_searcher} and profile.name = {name_query}


This is incorrect because it misses the part where it needs to get the status relative to the person doing the searching. E.g. it will give the following incorrect results for the third example:



If Fred searches for 'Jane': 2, 'Jane', 'active'


Notice how it gives a status of 'active' where it should be null because Fred does not have an active connection with Jane.





Aucun commentaire:

Enregistrer un commentaire