SQL Server共同的朋友数

时间:2016-08-23 08:10:21

标签: sql-server tsql

我正在尝试构建查询。要求是获得两个用户之间的共同朋友的数量。我需要为作为参数传递的单个userId做。但结果将是递归的。它就像一棵树。下表结构将为您提供有关要求的概念:

DECLARE @Person TABLE
(ID INT PRIMARY KEY,
Name VARCHAR(25))

DECLARE @Friendship TABLE
(PersonID INT,
 FriendID INT)

--Person table entry
INSERT @Person 
SELECT 1, 'A' UNION ALL
SELECT 2, 'B' UNION ALL
SELECT 3, 'C' UNION ALL
SELECT 4, 'D' 

--Person:Friend relationship entry
INSERT @Friendship 
SELECT 1, 2 UNION 
SELECT 1, 4 UNION 
SELECT 2, 1 UNION 
SELECT 2, 3 UNION 
SELECT 2, 4 UNION 
SELECT 3, 2 UNION 
SELECT 3, 4 UNION 
SELECT 4, 1 UNION 
SELECT 4, 2 UNION 
SELECT 4, 3

SELECT DISTINCT F1.*, F2.PersonID AS MutualFriend
FROM @Friendship AS F1
INNER JOIN @Friendship AS F2 ON F2.PersonID <> F1.PersonID AND F2.FriendID = F1.FriendID
INNER JOIN @Person AS P1 ON P1.ID = F1.PersonID 
INNER JOIN @Person AS P2 ON P2.ID = F2.FriendID 
JOIN @Person AS P3 ON P3.ID = F2.FriendID
WHERE F1.PersonID = 3--The person for which friends and mutual friends need to be found
ORDER BY F1.PersonID

以上是一个示例查询,提供以下输出:

PersonID    FriendID    MutualFriend
3           2           1
3           2           4
3           4           1
3           4           2

正如你所看到的,1不是3的朋友,它仍然在列表中。查询的所需输出是:

PersonID    FriendID    MutualFriend
3           2           4
3           4           2

有人可以帮助我查询吗?我最好是两个人之间的共同朋友的数量。

1 个答案:

答案 0 :(得分:1)

根据所需的输出,尝试替换您的选择:

SELECT F1.*, MAX(F2.PersonID) AS MutualFriend
FROM @Friendship AS F1
INNER JOIN @Friendship AS F2 ON F2.PersonID <> F1.PersonID AND F2.FriendID = F1.FriendID
INNER JOIN @Person AS P1 ON P1.ID = F1.PersonID 
INNER JOIN @Person AS P2 ON P2.ID = F2.FriendID 
JOIN @Person AS P3 ON P3.ID = F2.FriendID
WHERE F1.PersonID = 3
group by F1.personID,F1.FriendID