3

I have the following tables

  • user (id, name, email)
  • friendships (id, user_id, friend_id)

And I given user_id of the current user, I would like to show a list of all the users in the database by the number of mutual friends. I have no trouble writing an SQL query to get the mutual friends between two particular. I am stumped on how to get the mutual friends for all the users in one query.

Here's the query for getting mutual friends between user A and user 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

Any ideas?

4

2 回答 2

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
于 2012-05-17T20:41:50.630 回答
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

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

于 2012-05-17T20:29:26.297 回答