按共同朋友的数量排序

时间:2012-05-17 20:19:51

标签: sql language-agnostic

我有以下表格

  • 用户(身份证,姓名,电子邮件)
  • friendships(id,user_id,friend_id)

我给了当前用户的user_id,我想通过共同朋友的数量显示数据库中所有用户的列表。我编写SQL查询以获得两个特定的共同朋友没有任何问题。我很困惑如何在一个查询中为所有用户获取共同的朋友。

以下是在用户A和用户B之间获取共同朋友的查询

SELECT users.* FROM friendships AS a
    INNER JOIN friendships AS b
        ON a.user_id = :a_id AND b.user_id = :b_id AND a.friend_id = b.friend_id
    INNER JOIN users ON users.id = a.friend_id

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

SELECT
    users.id,
    users.name,
    users.email,
    count(distinct facebook_friendships.user_id)
FROM users
JOIN friendships AS a ON users.id = a.friend_id
JOIN facebook_friendships AS b
    ON b.user_id = a.user_id AND a.friend_id = b.friend_id
GROUP BY 1,2,3
ORDER BY 4 DESC

我不确定你的其他表的列是什么,但这个查询应该是关闭的

答案 1 :(得分:0)

你可以试试这样的事情

set nocount on;

-- Your existing table
declare @user table (id int, name varchar(25), email varchar(25)) 
insert into @user select 1,'user a','a@a.com'
insert into @user select 2,'user b','b@b.com'
insert into @user select 3,'user c','c@c.com'
insert into @user select 4,'user d','d@d.com'
insert into @user select 5,'user e','e@e.com'

-- Your existing table
declare @friendships table (id int identity, user_id int, friend_id int)
insert into @friendships select 1,2
insert into @friendships select 1,3
insert into @friendships select 1,4
insert into @friendships select 1,5

insert into @friendships select 2,1
insert into @friendships select 2,4

insert into @friendships select 3,1
insert into @friendships select 3,2
insert into @friendships select 3,5

insert into @friendships select 4,1
insert into @friendships select 4,2
insert into @friendships select 4,5

insert into @friendships select 5,1
insert into @friendships select 5,2
insert into @friendships select 5,3

/* Find users with mutual friends */
declare @id int;set @id=4;


-- My friends
declare @myfriends table (userid int)
insert into @myfriends
select friend_id 
from @friendships 
where user_id=@id
--select * from @myfriends

-- All other users who have mutual friends with me
;with cteMutualFriends (userid, mutualfriendcount) as (
    select user_id,COUNT(*) as mutual 
    from @friendships 
    where friend_id in (select userid from @myfriends) and user_id not in (@id)
    group by user_id
) select u.*,cteMutualFriends.mutualfriendcount 
from cteMutualFriends 
inner join @user u on cteMutualFriends.userid=u.id
order by cteMutualFriends.mutualfriendcount desc