返回非朋友但一起参加大多数活动的用户

时间:2016-10-12 20:37:33

标签: mysql sql

假设我有一个朋友和事件表,如下所示

FriendsTable {
  user1_ID
  user2_ID
}

Events Table {
   event_ID
   user_ID
}

在我的朋友表中,如果user1和user2是朋友,我只会将其存储在我的数据库中,其中user1<用户2。所以(1,2)将被发现,但(2,1)将不会。

我正试图找出一种方法来返回不是朋友但按降序参加相同事件的用户。例如,

Events_Table{
  1, 1  //user1 attended event1
  1, 2  //user2 also attended event1
  3, 1 //user1 attended event 2
  3, 3 //user 3 attended event 3
  4, 1 //user1 attended event 4
  4, 3 //user3 attended event 4
  3, 5 // user 5 attended event 3
}

User_table{
  1, 2 //user1 is friends with user 2
}

因此,由于用户1和3不是朋友,而是一起参加了活动3和4,而用户1和5不是朋友,而是参加活动3 结果将按顺序排列为(1,3)和(1,5),因为用户1和用户3有更多类似的有人参加活动。

我的想法

我不想长篇大论,但我想首先用它来找到不是另一个朋友的朋友

select * from (select distinct f1.user1_id as user1, f2.user2_id as
user2 from FriendsTable as f1, FriendsTable as f2 where 
f1.user1_id < f2.user2_id MINUS select * from FriendsTable

然后以某种方式将其加入事件表......

3 个答案:

答案 0 :(得分:0)

我会说首先找到在同一事件中参加的所有对然后减去朋友:

     select et1.event_ID, et1.user_id, et2.user_id 
       from Events_Table et1, Events_Table et2 
         where et1.event_ID=et2.event_ID and et1.user_ID < et2.user_id and 
           (et1.user_id, et2.user_id) not in (select user1_ID, user2_ID from FriendsTable)
        order by et1.event_ID, et1.user_id, et2.user_id ;

答案 1 :(得分:0)

您可以使用基于自我左连接的dinamic表

select * from 
events where event_ID in ( 

     select distintc e.event_ID
     from events  as e 
     left join FriendsTable as f1 on f1.user1_id = e.user_ID
     left join FriendsTable as f2 on f2.user1_id = e.user_ID
     where f1.user_ID is null 
     or f2.user_ID is null 
 )
 order by events, user_ID;

答案 2 :(得分:0)

select q1.user_ID1, q1.user_ID2 from
    (select ET1.event_ID event_ID, ET1.user_ID user_ID1, et2.user_ID user_ID2 
        from EventsTable ET1 inner join EventsTable ET2 on ET1.event_ID = ET2.event_ID
        where ET1.user_ID < ET2.user_ID and (select count(*) from FriendsTable where user1_ID = et1.user_id and user2_ID = et2.user_id) = 0) q1
group by q1.user_ID1, q1.user_ID2
order by count(*) desc