推荐朋友一度分离

时间:2017-05-19 11:00:07

标签: sql sql-server

我有一个表结构

(Xref) IDUser1 and IDUser2 and table IDUser, UserName.

朋友的外部参照表是双向的(1,2)和(2,1)。

最好的方法是让朋友的朋友(不是我的朋友)至少有一位朋友作为共同朋友?

2 个答案:

答案 0 :(得分:0)

SELECT DISTINCT friendL2.*
FROM [User] me

LEFT JOIN Xref relation1
ON relation1.IDUser1 = me.IDUser

LEFT JOIN Xref relation2
ON relation2.IDUser2 = me.IDUser

INNER JOIN [User] friendL1
ON relation1.IDUser2 = friendL1.IDUser
OR relation2.IDUser1 = friendL1.IDUser

LEFT JOIN Xref relation3
ON relation3.IDUser1 = friendL1.IDUser

LEFT JOIN Xref relation4
ON relation4.IDUser2 = friendL1.IDUser

INNER JOIN [User] friendL2
ON relation3.IDUser2 = friendL2.IDUser
OR relation4.IDUser1 = friendL2.IDUser

WHERE friendL2.IDUser != friendL1.IDUser -- This will tell that this guy can't be your friend
AND me.IDUser = @me

只需将@me替换为您当前的ID

即可

如果您希望按UserName过滤

,也可以修改下一行的最后一行
AND me.Username = @me

答案 1 :(得分:-1)

IDUser1    |    IDUser2
1          |    2
2          |    1
           |    

Sory对于不完整的问题,这是我的表Xref,而我有另一个表User(IDUser,UserName)。 IDUser 1的用户是IDUser 2的朋友,反之亦然。

我对朋友的朋友有这个查询

SELECT DISTINCT u.IDUser1,p.Username FROM Xref AS u 
inner join User as p on p.IDuser1=u.IDUser1
INNER JOIN (SELECT g.IDUser2 FROM Xref AS g WHERE g.IDUser1 = @IDUsern1
) AS f ON 
(u.IDUser2=f.IDUser2 AND u.IDUser1 <> @IDUser2)
WHERE U.IDUser1 NOT IN (Select Xref.IDUser2 from xref 
inner join Users on Users.IDUser1=Xref.IDuser1
where xref.IDUser2=@IDUser)

这很有效,但我需要不是我的朋友但至少有一个朋友作为共同朋友的用户