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:
CREATE TABLE dbo.Person
(ID INT PRIMARY KEY,
Name VARCHAR(25))
CREATE TABLE dbo.Friendship
(PersonID INT,
FriendID INT)
Data insertion:
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')
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:
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:
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