共同朋友的SQL查询

时间:2011-07-14 23:17:18

标签: mysql sql

我的MySQL表格结构是这样的。

USER
uid

FRIENDS
fuid,fuid2,fapproved

对于每个朋友关系,我在FRIENDS中插入2条记录。如果用户1是用户2的朋友,则将下一行插入FRIENDS

1,2,1

2,1,1

1,3,1

3,1,1

2,3,1

3,2,1

用户ID 3是用户ID 1和用户ID 2的朋友

如何在一个SQL查询中获取用户ID 3?

6 个答案:

答案 0 :(得分:2)

鉴于两个用户@ friend1和@ friend2找到所有共同朋友的用户:

SELECT user.uid
FROM user
WHERE EXISTS(
    SELECT TOP 1 1 
    FROM Friends 
    WHERE Friends.fuid = @friend1 AND Friends.fapproved = 1 
      AND Friends.fuid2 = User.uid
  )
  AND EXISTS(
    SELECT TOP 1 1 
    FROM Friends 
    WHERE Friends.fuid = @friend2 AND Friends.fapproved = 1 
      AND Friends.fuid2 = User.uid
  )

答案 1 :(得分:1)

试试这个:

SELECT DISTINCT a.*
    FROM user  a, friends b, friends c
WHERE b.fuid = c.fuid2
    AND b.fuid2 = a.uid
    AND c.fuid = a.uid
    AND b.fapproved = 1
    AND c.fapproved = 1

测试脚本(在MS SQL中尝试过..):

CREATE TABLE #USER
(
    uid INT
)

INSERT #USER VALUES(1)
INSERT #USER VALUES(2)
INSERT #USER VALUES(3)


CREATE TABLE #FRIENDS
(
    fuid INT,
    fuid2 INT,
    fapproved  INT
)


INSERT #FRIENDS VALUES(1,2,1)
INSERT #FRIENDS VALUES(2,1,1)
INSERT #FRIENDS VALUES(1,3,1)
INSERT #FRIENDS VALUES(3,1,1)
INSERT #FRIENDS VALUES(2,3,1)
INSERT #FRIENDS VALUES(3,2,1)


SELECT DISTINCT a.*     
    FROM #user  a, #friends b, #friends c 
 WHERE b.fuid = c.fuid2     
     AND b.fuid2 = a.uid     
   AND c.fuid = a.uid     
   AND b.fapproved = 1     
     AND c.fapproved = 1 

答案 2 :(得分:1)

$query = "SELECT DISTINCT a.* FROM user  a, visitor b, visitor c WHERE b.user_id = c.visitor_id  AND b.visitor_id = a.user_id AND c.user_id = a.user_id AND b.user_id=65";
我尝试过了。它正在发挥作用。

答案 3 :(得分:0)

$query = "SELECT f.fuid, f.fuid2 FROM FRIENDS f, USER u WHERE (f.fuid = u.uid or f.fuid2 = u.uid) AND (u.uid = ".$uid.";");

是你在寻找什么?

答案 4 :(得分:0)

IMO通过友谊表上的自我加入找到共同的朋友更直观

SELECT a.fuid2 FROM facebook_friendships AS b
    ON a.fuid = :user_a AND b.fuid = :user_b AND a.fuid2 = b.fuid2
    AND a.fapproved = 1 AND b.fapproved = 1

以下是英语的重要条件:

  • a.fuid =:user_a - 用户A是友谊A中用户X的朋友
  • b.fuid =:user_b - 用户B是友谊B中用户Y的朋友
  • a.fuid2 = b.fuid2 - 用户A和用户B是具有相同用户的朋友(即X和Y是同一用户)

所以你基本上抓住了我上面列出的条件的所有行。您可能会得到重复的结果,因此在a.fuid2周围添加DISTINCT将是一个好主意。

答案 5 :(得分:0)

我刚刚启动MySQL,我遇到了这个问题。

personID    friendID
6           10
6           2
6           3
8           1
8           2
8           3

/*  query for friends   */
select f.personID, p.personID, firstName, lastName
from person p
inner join friends f on f.friendID = p.personID
where f.personID = 6;

/*  query for common friends    */
select f1.personID 'personID 1', f2.personID 'personID 2', f1.friendID 'common friend'
from person p
inner join friends f1 on f1.friendID = p.personID
inner join friends f2 on f2.friendID = p.personID
where f1.personID = 6 and f2.personID = 8 and f1.friendID = f2.friendID;

结果:

personID 1    personID 2    common friend
6             8             2
6             8             3

虽然它不是您问题的直接解决方案,但您可以在此处找到解决方案。