6

我试图弄清楚如何为 SQL Server 编写一个用于匹配共同朋友的查询。名称位于同一个表的两列中。只应返回“已接受”的朋友。

以下是数据库信息的示例:

ID     Name_1     Name_2     Accepted
=====================================
1      Jimmy      John       1
2      John       Joey       1
3      Joey       Jimmy      1
4      John       Sally      1
5      Jimmy      Sally      0

在这个例子中,Jimmy 是 John 的朋友。这两个人(和期望的结果)之间的共同朋友是乔伊。莎莉也是两人的共同点,但吉米还没有接受她为朋友。

4

2 回答 2

3

尝试使用这种双重自我加入来建立相互友谊:

SELECT Friend_1, Friend_2, COMMON
FROM
(
SELECT f2.NAME_1 AS Friend_1
      ,f1.NAME_2 AS Friend_2
      ,f2.Name_2 AS COMMON
FROM friends f1
INNER JOIN friends f2
ON f1.NAME_1 = f2.NAME_2
WHERE f1.accepted = 1 AND f2.accepted = 1
) T
INNER JOIN FRIENDS F3
ON (F3.Name_1 = Friend_1 AND F3.Name_2 = Friend_2)
OR (F3.Name_2 = Friend_1 AND F3.Name_1 = Friend_2)
WHERE F3.ACCEPTED <> 0 AND Friend_1 = 'John' AND Friend_2 = 'Jimmy'

COMMON 是共同的朋友。

相关的 SQL 小提琴

注意:我不确定这种结构是保持这种关系的最佳结构,你有关于相互友谊的规则,关于拒绝友谊,但看起来你对这些信息一无所知。您只知道部分信息还是这是您的存储系统/架构?

于 2013-05-31T14:00:05.173 回答
0

A somewhat less elegant looking, but possibly more performing solution could be:

DECLARE @person1 VARCHAR(50) = 'Jimmy'
DECLARE @person2 VARCHAR(50) = 'John'

SELECT  FriendsOfP1.Name as MutualFriend
FROM    ( SELECT    A.name_2 AS Name
          FROM      friends A
          WHERE     ( A.name_1 = @person1 )
                    AND Accepted = 1
                    AND name_2 <> @person2
          UNION ALL
          SELECT    A.name_1
          FROM      friends A
          WHERE     ( A.name_2 = @person1 )
                    AND Accepted = 1
                    AND name_1 <> @person2 ) AS friendsOfP1
INNER JOIN ( SELECT A.name_2 AS Name
             FROM   friends A
             WHERE  ( A.name_1 = @person2 )
                    AND Accepted = 1
                    AND name_2 <> @person1
             UNION ALL
             SELECT A.name_1
             FROM   friends A
             WHERE  ( A.name_2 = @person2 )
                    AND Accepted = 1
                    AND name_1 <> @person1 ) AS FriendsOfP2
ON      FriendsOfP1.Name = FriendsOfP2.Name 
于 2013-05-31T14:53:11.010 回答