我正在研究“你可能认识的人”功能。我有两张桌子:
USERS
ID
电子邮件
命名
等
友谊
USER_ID
friend_id
对于每个友谊我都会做两个记录。假设用户7和9成为朋友...我会在友谊表中创建user_id = 7,friend_id = 9和另一个user_id = 9,friend_id = 7的记录。
我如何制作一个sql查询,根据我朋友的朋友建议我可能知道的人?我也希望它是根据最共同的朋友订购的。
答案 0 :(得分:7)
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
我会在哪里开始。
答案 1 :(得分:0)
Select friend_id from friendships where user_id IN (select friendid from freindships where userid = <userid>)
考虑用户7和9是朋友。对于用户7,此查询将为您提供用户9的朋友列表。
答案 2 :(得分:0)
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
答案 3 :(得分:0)
您可以使用以下查询;
<强>查询强>:
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"] + "'
注意:状态可能是&#34; 1 &#34;,&#34; 0 &#34;,&#34; 2 强>&#34;作为默认参数。他们的意思是;
1 :确认 0 :尚未确认 2 :拒绝
我通过这些参数编写了上面的查询代码。你的也可能是这样的。
放轻松!