Click here to Skip to main content
15,906,558 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have table friend_master where I store user's id and friend's id.
Now I would like to display mutual friends in my project in GridView.

I would like the SQL query for that, can any one help me out?

Thanks in advanced.
Posted
Updated 8-Nov-11 5:16am
v2

1 solution

Below the are the SQL statements for getting:
- The mutual friends of two specific persons
- Total list of all persons and the mutual friends they have with the other persons.

For testing I added table creation and data insertion statements.

Table creation:
SQL
CREATE TABLE dbo.Person
(ID INT PRIMARY KEY,
 Name VARCHAR(25))

CREATE TABLE dbo.Friendship
(PersonID INT,
 FriendID INT)

Data insertion:
SQL
INSERT INTO dbo.Person VALUES ( 1, 'Person01')
INSERT INTO dbo.Person VALUES ( 2, 'Person02')
INSERT INTO dbo.Person VALUES ( 3, 'Person03')
INSERT INTO dbo.Person VALUES ( 4, 'Person04')

-- The Friendship table stores the friendship between two persons
-- in both directions. So the friendship between Person01 and
-- and Person02 is stored as (1, 2) and (2, 1). When inserting or
-- deleting friendships both record need inserting or removing.
INSERT INTO dbo.Friendship VALUES (1, 2)
INSERT INTO dbo.Friendship VALUES (1, 4)
INSERT INTO dbo.Friendship VALUES (2, 1)
INSERT INTO dbo.Friendship VALUES (2, 3)
INSERT INTO dbo.Friendship VALUES (2, 4)
INSERT INTO dbo.Friendship VALUES (3, 2)
INSERT INTO dbo.Friendship VALUES (3, 4)
INSERT INTO dbo.Friendship VALUES (4, 1)
INSERT INTO dbo.Friendship VALUES (4, 2)
INSERT INTO dbo.Friendship VALUES (4, 3)


Mutual friends for Person01 and Person02:
SQL
SELECT P1.Name
FROM dbo.Friendship AS F1
JOIN dbo.Person AS P1 ON P1.ID = F1.FriendID
WHERE F1.PersonID = 1 AND
      F1.FriendID IN (SELECT F2.FriendID
                      FROM dbo.Friendship AS F2
                      WHERE F2.PersonID = 2)

List of mutual friends for all persons:
SQL
SELECT P1.Name, P2.Name, P3.Name AS MutualFriend
FROM dbo.Friendship AS F1
JOIN dbo.Friendship AS F2 ON F2.PersonID <> F1.PersonID AND F2.FriendID = F1.FriendID
JOIN dbo.Person AS P1 ON P1.ID = F1.PersonID
JOIN dbo.Person AS P2 ON P2.ID = F2.PersonID
JOIN dbo.Person AS P3 ON P3.ID = F2.FriendID
ORDER BY F1.PersonID, F2.PersonID
 
Share this answer
 
Comments
Ali Manam 6-Jul-19 18:32pm    
What is the equivalent code of this solution to Linq or Lambda?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900