互助的朋友sql(Mysql)

时间:2011-07-18 10:25:09

标签: mysql sql

我有两张桌子

用户表:

id|name

user_relationships

id | user_id | friend_id

并希望获得2位用户的共同朋友的名字。即:

user_relationships
1 | 1 | 3
2 | 2 | 3  

users
3| sammy

用户1和2有共同的朋友3.我想在一个查询中得到他的名字'sammy'。

我该怎么做?

4 个答案:

答案 0 :(得分:6)

您需要将user_relationships与自身相关联,以便具有不同user_id的两行具有相同的friend_id

所有共同的朋友:

select ur1.user_id user1, 
       ur2.user_id user2, 
       ur2.friend_id mutual_friend
from   user_relationships ur1 
       JOIN user_relationships ur2 ON  ur1.friend_id = ur2.friend_id
where  ur1.user_id != ur2.user_id

加入users表以获取名称:

select ur1.user_id user_id1, 
        u1.name User1, 
       ur2.user_id user2, 
        u2.name User2,
       ur2.friend_id mutual_friend_id,
        u3.name mutual_friend
from user_relationships ur1 
     JOIN user_relationships ur2 ON  ur1.friend_id = ur2.friend_id
     JOIN user u1 ON u1.user_id = ur1.user_id
     JOIN user u2 ON u1.user_id = ur2.user_id
     JOIN user u3 ON ur1.user_id = u3.user_id
where ur1.user_id != ur2.user_id

您可以使用ur1.user_id = first_userur2.user_id = second_user

过滤某些特定用户的共同朋友

答案 1 :(得分:6)

SELECT id, name
FROM users
WHERE id IN (
  SELECT friend_id
  FROM user_relationships
  WHERE user_id IN ( 1, 2 )
  GROUP BY friend_id
  HAVING COUNT(friend_id) >= 2
)

或一次加入:

SELECT friend_id, name
FROM user_relationships r
  INNER JOIN users u ON r.friend_id = u.id
WHERE user_id IN ( 1, 2 )
GROUP BY friend_id
HAVING COUNT(friend_id) >= 2

答案 2 :(得分:0)

您可以尝试这样的事情:

select id, name from users where id in 
    (select friend_id from user_relationships where user_id = @user1_id and friend_id in 
        (select friend_id from user_relationships where user_id = @user2_id)
    )

这应该返回ID为@ user1_id和@ user2_id的所有用户的共同朋友。 它还没有测试过,但应该提供一个起点...

答案 3 :(得分:0)

没有检查它,但是此查询应该为您提供ID [no]的相关用户名列表。

select u1.name, u2.name 
  from users as u1
  join user_relationships as ur
    on u1.id = ur.user_id
  join users as u2
    on ur.friend_id = u2.id
  where U1.id = [no];

顺便说一下,您的交叉表不需要人工ID,因为(user_id,friend_id)已经是合法的主键。