【问题标题】:Sort by number of mutual friends按共同好友的数量排序
【发布时间】:2012-05-25 10:55:15
【问题描述】:

我有以下表格

  • 用户(ID、姓名、电子邮件)
  • 友谊(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

有什么想法吗?

【问题讨论】:

  • 你能发布一些示例数据吗...

标签: sql language-agnostic


【解决方案1】:

你可以试试这样的

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

【讨论】:

    【解决方案2】:
    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
    

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

    【讨论】:

      猜你喜欢
      • 2011-12-08
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多