代码之家  ›  专栏  ›  技术社区  ›  tybro0103

“您可能认识的人”SQL查询

  •  4
  • tybro0103  · 技术社区  · 14 年前

    我正在开发一个“你可能认识的人”功能。我有两张桌子:

    用户
    身份证件
    电子邮件
    名称

    友谊
    用户ID
    朋友ID

    我为每一次友谊做了两张唱片。假设用户7和9成为朋友…我会在友谊表中记录用户_id=7、朋友_id=9和另一个用户_id=9、朋友_id=7的位置。

    我如何进行一个SQL查询,根据我朋友的朋友来提示我可能认识的人?我也希望它是基于大多数共同的朋友来订购的。

    4 回复  |  直到 8 年前
        1
  •  7
  •   Justin Niessner    14 年前
    select u.id, u.email, u.name, u.etc
    -- Get all my friends
    from Friendships as f1
    -- Get their friends
    inner join Friendships as f2
        on f1.friend_id = f2.user_id
    -- Get their friends User information
    inner join Users as u
        on f2.friend_id = u.id
    where f1.user_id = @userId
    

    会是我开始的地方。

        2
  •  0
  •   pavanred    14 年前
    Select friend_id from friendships where user_id IN (select friendid from freindships where userid = <userid>)
    

    考虑到用户7和9是朋友。对于用户7,此查询将为您提供用户9的朋友列表。

        3
  •  0
  •   Roopesh Shenoy    14 年前
    select * from 
    (select distinct friendsOfFriends.friends_id, count(1) as mutualfriends
      from FRIENDSHIPS friendsOfFriends
     inner join FRIENDSHIPS friends ON friends.friend_id = friendsOfFriends.user_id
      where friends.user_id = @myuserid
      group by friendsOfFriends.friends_id) t
    order by mutualfriends desc
    
        4
  •  0
  •   Ali Akyıldırım    8 年前

    您可以使用下面的查询;

    查询 :

    Select * from [USERS] U where id not in 
    ((select F.friend_id as id from [FRIENDSHIPS] f where f.user_id='" + Session["UserId"] + "' and f.Status=1)
    union (select F.user_id as id from [FRIENDSHIPS] f where f.friend_id='" + Session["UserId"] + "' and f.Status=1)
    union (select F.friend_id as id from [FRIENDSHIPS] f where f.user_id='" + Session["UserId"] + "' and f.Status=0)
    union (select F.friend_id as id from [FRIENDSHIPS] f where f.user_id='" + Session["UserId"] + "' and f.Status=2))
    and U.id !='" + Session["UserId"] + "'
    

    注意:状态可能是“ “,” “,” “作为默认参数。它们的含义是;

    :已确认 :尚未确认 :拒绝

    我根据这些参数编写了上面的查询代码。你的也可能是这样。

    别紧张!