Friend Requests II: Who Has the Most Friends
You can write a query to find the person who has the most friends by counting the number of friends for each user and then selecting the user with the maximum number. Here’s the query:
|
|
Explanation:
- The subquery inside the
FROM
clause first combinesrequester_id
andaccepter_id
from theRequestAccepted
table using theUNION ALL
operator. This ensures that we consider both the requesters and accepters as potential friends. - Then, the outer query groups the results by
person_id
and counts the number of friends for each person. - Finally, the main query orders the results by the friend count in descending order and selects the first row using
LIMIT 1
, which gives the person with the most friends.