I'm working on a social web-site project and I need to list "First, Second and Third Degree Contacts" of my contacts. I'm using SQL Server AND C#
Assume a contact
table like this:
For first degree contact:
- If
gulsah
is me then my first degree contacts areburak,sennur
Query I use to select this:
SELECT contact_2 FROM Contacts_Table WHERE contact_1 like 'gulsah'
For second degree contact:
If gulsah
is me again then my second degree contacts are: mali
What makes it difficult is to select contacts of my contacts who are not my first degree contact.
I can select mutual contacts but I guess it is not the right approach.
For example, to select mutual contacts of me (gulsah
) and burak
:
SELECT contact_1 FROM (SELECT * FROM Contact_Test
WHERE contact_2 like 'burak') a
INNER JOIN (SELECT contact_1 FROM Contact_Test
WHERE (contact_2 = 'gulsah')) b
ON a.contact_1 = b.contact_1
This query works but as I said, it's not the right approach for this job.
For third degree contact:
If gulsah
is me again then my third degree contacts are_ mehmet,ahmet
I need to select contacts of my contacts' contacts who are not my first and second degree contact :)
Here is a post from Linkedin which explains contact level.
Thanks for responses.
You could use the
EXCEPT
operator.First-degree contacts:
Second-degree contacts who are not first-degree contacts:
EXCEPT
tells SQL server to return all the results from the firstSELECT
that do NOT appear in the secondSELECT
.For third-degree contacts (who are not first- or second-degree contacts):
I don't hold high hopes for performance, but of course you will need to check this yourself.
As a side note:
Use
INTERSECT
for this.maybe this helps: http://techportal.ibuildings.com/2009/09/07/graphs-in-the-database-sql-meets-social-networks/
Here's my approach:
Add my contact to a special collected contact list.
For every contact in the collected list as
Contact_1
of the contact table, add its correspondingContact_2
unless that contact is already in the collected list.Repeat step #2 the number of times that is the target degree number minus one.
Repeat the query in step #2 once more, but this time simply return the result set (do not add the rows to the collected list).
The script:
As you can see, both the degree number and 'my' contact are parametrisable. I'm using the
varchar
type for contacts, but that of course can easily be replaced withint
, if needed.