Sql得到了不是我朋友的朋友的所有朋友

时间:2011-10-19 10:07:56

标签: mysql sql

我正在制作一个“可能的朋友”功能。我需要向所有不是我朋友的朋友的朋友展示,也不要发送给我或者没有我的未决请求

FRIENDSHIPS
user_id
friend_id
status  (0 = pending, 1 = approved) 

对于每个友谊我都会做两个记录。假设用户1和2成为朋友......我会在where user_id=1,friend_id=2表格中记录where user_id=2, friend_id=1和另一个friendships

当第一个用户发送请求时,将状态设置为0,当朋友接受请求时,我会用1更新两行

如何基于我朋友的朋友制作一个建议“可能的朋友”的SQL查询?

4 个答案:

答案 0 :(得分:7)

在这里你......简单的加入

SELECT F2.friend_id
FROM FRIENDSHIPS F
JOIN FRIENDSHIPS F2 ON F.friend_id = F2.user_id
WHERE F2.friend_id NOT IN (SELECT friend_ID FROM FRIENDSHIPS WHERE user_id = @user_id)
  AND F.user_id = @user_id

答案 1 :(得分:0)

我认为你也可以使用子查询(?)来检索相同的信息。

SELECT friend_id     来自朋友     WHERE user_id IN     (SELECT friend_ID FROM FRIENDSHIPS WHERE user_id = @ YOURUSER_ID AND status = 1)     AND friend_id<> @YOURUSER_ID

SELECT friend_id 
FROM FRIENDSHIPS
WHERE user_id IN
(SELECT friend_ID FROM FRIENDSHIPS WHERE user_id=@YOURUSER_ID AND status=1)
AND friend_id NOT IN
(SELECT friend_ID FROM FRIENDSHIPS WHERE user_id=@YOURUSER_ID AND status=1)
AND friend_id<>@YOURUSER_ID

我认为会有效但连接方法要简单得多。

答案 2 :(得分:0)

试试这个: - )

select * from FRIENDSHIPS pf 
JOIN FRIENDSHIPS f ON pf.friend_id=f.user_id AND pf.status=1 AND f.status=1   
JOIN FRIENDSHIPS me ON me.user_id = f.friend_id AND me.user_id = MY_USER_ID AND me.status=1 AND f.status=1 
WHERE me.user_id <> pf.friend_id AND me.friend_id <> pf.user_id

答案 3 :(得分:-1)

请试试这个 - &gt; :)

SELECT f2.friend_id
FROM FRIENDSHIPS f1
JOIN FRIENDSHIPS f2
ON f1.friend_id=f2.user_id
WHERE f2.friend_id NOT IN (select friend_id from FRIENDSHIPS where user_id=@user_id)
AND f1.user_id=@user_id
AND f2.friend_id!=@user_id