内部查询只发给第一人的FRIEND ID,并将其标准化为“FriendID”一栏。 如果记录中发现有一人ID = 1人处于第一个岗位,那么它会 gr第二个职位......如果人ID = 1人处于第二个职位,那么它就 gr了第一个职位。
With that being done, we know who the single list of friends are of person 1... Done. Now, join back to the friendship table again, but only for those that FIRST are qualified as one of the friends from person 1... Once that is qualified, then make sure that the other person on the second table is the person 3 that you are looking for the commonality of.
• 确保个人指数1 和他人指数2 ,以利用OR条件。
select
JustPerson1Friends.FriendID
from
( select
if( f.Person1 = 1, f.Person2, f.Person1 ) as FriendID
from
Friendships f
where
( f.Person1 = 1
OR f.Person2 = 1 )
AND f.status = "friend" ) JustPerson1Friends
JOIN Friendships f2
on ( JustPerson1Friends.FriendID = f2.Person1
OR JustPerson1Friends.FriendID = f2.Person2 )
AND f2.status = "friend"
AND ( f2.Person1 = 3 OR f2.person2 = 3 )
另一种选择是,将“3”作为共同选择列入结果,因此我们不需要在3年后明确限定。 此外,通过使用MySQL Variables,易于描述和执行作为参数。 在内部询问之后,DOUBLE在友谊中留下来,以明确检验在X/Y或Y/X组合中找到一个人的包裹。 因此,最后条款只是说什么。 只要在ESTHER LEFT-JOIN的条件下找到记录,就有一名共同的朋友,并列入结果。
select
JustPerson1Friends.FriendID
from
( select
@WantPerson2 as FindInCommonWith,
if( f.Person1 = @WantPerson1, f.Person2, f.Person1 ) as FriendID
from
( select @WantPerson1 := 1,
@WantPerson2 := 3 ) sqlvars
Friendships f,
(
where
( f.Person1 = @WantPerson1
OR f.Person2 = @WantPerson2 )
AND f.status = "friend" ) JustPerson1Friends
LEFT JOIN Friendships f2
on JustPerson1Friends.FindInCommonWith = f2.Person1
AND JustPerson1Friends.FriendID = f2.Person2
AND f2.status = "friend"
LEFT JOIN Friendships f3
on JustPerson1Friends.FindInCommonWith = f2.Person2
AND JustPerson1Friends.FriendID = f2.Person1
AND f2.status = "friend"
where
f2.Person1 > 0
OR f3.Person1 > 0