Approach: Union requester_id and accepter_id [Accepted]
Being friends is bidirectional, so if one person accepts a request from another person, both of them will have one more friend.
Thus, we can union column requester_id and accepter_id, and then count the number of the occurrence of each person.
select requester_id as ids from request_accepted union all select accepter_id from request_accepted;
Note: Here we should use
union allinstead of
union allwill keep all the records even the 'duplicated' one.
Taking the sample as an example, the output is:
Then it will be fairly easy to get the 'ids' with most occurrence using the same technique as mentioned in problem 580. Customer Placing the Largest Number of Orders.
select ids as id, cnt as num from ( select ids, count(*) as cnt from ( select requester_id as ids from request_accepted union all select accepter_id from request_accepted ) as tbl1 group by ids ) as tbl2 order by cnt desc limit 1 ;