获得我有朋友的用户

时间:2014-03-25 15:09:45

标签: mysql sql

有两个sql表:

1)"用户"具有以下结构和数据:

user_id,user_name

 1, John
 2, Mike
 3, Chris
 4, Paul
 5, Kelly
 6, Kevin

2)"用户朋友"它包含了友好关系,具有以下结构和数据:

userfriends_user_id,userfriends_friend_id

 1, 2 => [ John is friend with Mike ]
 2, 3 => [ Mike is friend with Chris]
 2, 4 => [ Mike is friend with Paul ]
 5, 1 => [ Kelly is friend with John]
 6, 5 => [ Kevin is friend with Kelly]

我想创建一个SELECT(user_name,user_id)来获取John与其有共同朋友的用户,因此输出应该是Chris,Paul,Kevin。这可以只在一个选择声明中完成吗?

3 个答案:

答案 0 :(得分:1)

你可以通过吸引朋友的所有朋友来做到这一点。这需要从userfriends表连接到自身。

然后,看看朋友的朋友"这不止一次出现。您可以使用group byhaving

执行此操作
select uff.userfriends_friend_id
from userfriends uf join
     userfriends uff
     on uf.userfriends_friend_id = uff.userfriends_user_id
where uf.userfriends_user_id = 1
group by uff.userfriends_friend_id
having count(*) > 1;

答案 1 :(得分:0)

好吧,我现在还不知道我是不是觉得太复杂了。以下是我提出的建议:

select * from users
where user_id in
(
  select user1_id
  from
  ( -- users except John and their friends (again except John)
    select userfriends_user_id as user1_id, userfriends_friend_id as user2_id 
    from userfriends where userfriends_user_id != 1 and userfriends_friend_id != 1
    union 
    select userfriends_friend_id as user1_id, userfriends_user_id as user2_id 
    from userfriends where userfriends_user_id != 1 and userfriends_friend_id != 1
  ) others
  where user2_id in
  ( -- friends of John's
    select userfriends_user_id from userfriends where userfriends_friend_id = 1
    union
    select userfriends_friend_id from userfriends where userfriends_user_id = 1
  )
);

这是SQL小提琴:http://sqlfiddle.com/#!2/338d87/1

答案 2 :(得分:0)

测试此查询:

SELECT * FROM users
WHERE user_id IN
(
    SELECT uf.userfriends_friend_id AS CommonId
    FROM userfriends uf, 
        (
            SELECT uf2.userfriends_friend_id
            FROM userfriends uf2
            WHERE uf2.userfriends_user_id = 1
        ) A
    WHERE uf.userfriends_user_id = A.userfriends_friend_id

    UNION

    SELECT uf.userfriends_user_id  AS CommonId
    FROM userfriends uf, 
        (
            SELECT uf2.userfriends_user_id
            FROM userfriends uf2
            WHERE uf2.userfriends_friend_id = 1
        ) A
    WHERE uf.userfriends_friend_id = A.userfriends_user_id
)

我测试了@Thorsten Kettner提供的SQLfiddle。有用。输出是正确的。谢谢@Thorsten Kettner!