request_accepted
holds the data of friend acceptance, while requester_id and accepter_id both are the id of a person.
| requester_id | accepter_id | accept_date| |--------------|-------------|------------| | 1 | 2 | 2016_06-03 | | 1 | 3 | 2016-06-08 | | 2 | 3 | 2016-06-08 | | 3 | 4 | 2016-06-09 |Write a query to find the the people who has most friends and the most friends number. For the sample data above, the result is:
| id | num | |----|-----| | 3 | 3 |Note:
Algorithm
\nBeing friends is bidirectional, so if one person accepts a request from another person, both of them will have one more friend.
\nThus, we can union column requester_id and accepter_id, and then count the number of the occurrence of each person.
\nselect requester_id as ids from request_accepted\nunion all\nselect accepter_id from request_accepted;\n
\n\nNote: Here we should use
\nunion all
instead ofunion
becauseunion all
will keep all the records even the \'duplicated\' one.
Taking the sample as an example, the output is:
\nids | \n
---|
1 | \n
1 | \n
2 | \n
3 | \n
2 | \n
3 | \n
3 | \n
4 | \n
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.
\nMySQL
\nselect ids as id, cnt as num\nfrom\n(\nselect ids, count(*) as cnt\n from\n (\n select requester_id as ids from request_accepted\n union all\n select accepter_id from request_accepted\n ) as tbl1\n group by ids\n ) as tbl2\norder by cnt desc\nlimit 1\n;\n