[SQL 문제 풀이] Friend Requests II: Who Has the Most Friends (친구 요청 II: 가장 많은 친구가 있는 사람)

Stupefyee's avatar
Jun 09, 2025
[SQL 문제 풀이] Friend Requests II: Who Has the Most Friends (친구 요청 II: 가장 많은 친구가 있는 사람)
Friend Requests II: Who Has the Most Friends - LeetCode
Can you solve this real interview question? Friend Requests II: Who Has the Most Friends - Table: RequestAccepted +----------------+---------+ | Column Name | Type | +----------------+---------+ | requester_id | int | | accepter_id | int | | accept_date | date | +----------------+---------+ (requester_id, accepter_id) is the primary key (combination of columns with unique values) for this table. This table contains the ID of the user who sent the request, the ID of the user who received the request, and the date when the request was accepted.   Write a solution to find the people who have the most friends and the most friends number. The test cases are generated so that only one person has the most friends. The result format is in the following example.   Example 1: Input: RequestAccepted table: +--------------+-------------+-------------+ | 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 | +--------------+-------------+-------------+ Output: +----+-----+ | id | num | +----+-----+ | 3 | 3 | +----+-----+ Explanation: The person with id 3 is a friend of people 1, 2, and 4, so he has three friends in total, which is the most number than any others.   Follow up: In the real world, multiple people could have the same most number of friends. Could you find all these people in this case?
Friend Requests II: Who Has the Most Friends - LeetCode
notion image
가장 많은 친구와 가장 많은 친구 수를 가진 사람들을 찾기 위한 해결책을 작성하세요. 테스트 케이스는 한 사람만이 가장 많은 친구를 가질 수 있도록 생성됩니다.
 

내가 작성한 쿼리

Oracle

SELECT * FROM ( SELECT id, COUNT(*) AS num FROM ( SELECT requester_id AS id FROM RequestAccepted UNION ALL SELECT accepter_id AS id FROM RequestAccepted ) GROUP BY id ORDER BY num DESC ) WHERE ROWNUM = 1;

MySQL

SELECT id, COUNT(*) AS num FROM ( -- 친구 관계는 양방향이므로, 둘 중 어디든 나오면 친구 카운트 증가 SELECT requester_id AS id FROM RequestAccepted UNION ALL SELECT accepter_id AS id FROM RequestAccepted ) AS all_ids GROUP BY id -- 사람별로 친구 수 집계 ORDER BY num DESC -- 친구 수가 많은 순으로 정렬 LIMIT 1; -- 가장 친구가 많은 사람 한 명만 출력

차이점

  • 상위 결과값 출력 개수 제한하는 방식의 차이
Share article

stupefyee