To solve this problem, we need to identify all unique pairs of friends where both individuals are older than 25 years. We assume there are two tables:
Users: Contains user details (user_id, age).Friends: Contains friendship relationships (user_id, friend_id).
Approach
- Join Tables: Link the
Friendstable with theUserstable twice—once to get the age of the user and once to get the age of their friend. - Filter Ages: Ensure both the user and their friend are older than 25.
- Avoid Duplicates: Since friendships are mutual (e.g., (A,B) and (B,A) are the same), enforce
user_id < friend_idto list each pair only once.
Solution Code
SELECT f.user_id, f.friend_id
FROM Friends f
INNER JOIN Users u ON u.user_id = f.user_id
INNER JOIN Users uf ON uf.user_id = f.friend_id
WHERE u.age > 25
AND uf.age > 25
AND f.user_id < f.friend_id;
Explanation
- Joining Tables: The
INNER JOINwithUsers(aliased asuanduf) retrieves the age of both the user and their friend. - Age Filter: The
WHEREclause checks if both ages are greater than 25. - Unique Pairs: The condition
f.user_id < f.friend_idensures each friendship is listed once, avoiding duplicate entries like (A,B) and (B,A).
This query efficiently returns all valid friend pairs meeting the criteria. If the Friends table uses a different structure (e.g., user1_id and user2_id), replace user_id and friend_id with those column names while keeping the logic the same.


作者声明:本文包含人工智能生成内容。