SQL新手求助:基于跨表ID查询指定用户所有好友姓名的语句编写
Hey there! Glad you're diving into SQL—let's walk through how to solve this problem step by step. This is a classic example of joining two tables to pull related data, so it's a great foundational query to learn.
First, let's start with some reasonable assumptions about your table structures (since you didn't specify exact names/columns):
- Users table (let's call it
users): Contains user details with columns likeuser_id(unique identifier),first_name,last_name, and other user-specific info. - Friends table (let's call it
friends): Tracks friendships with columnsuser_id(the main user) andfriend_user_id(the user's friend).
The SQL Query
Here's the query that will get you John Doe's friends' first and last names:
SELECT u.first_name, u.last_name FROM users u JOIN friends f ON u.user_id = f.friend_user_id WHERE f.user_id = ( SELECT user_id FROM users WHERE first_name = 'John' AND last_name = 'Doe' );
Let's Break It Down
- Subquery: The inner
SELECT user_id FROM users WHERE first_name = 'John' AND last_name = 'Doe'first finds the uniqueuser_idfor John Doe—this is how we link him to his friends in thefriendstable. - JOIN: We join the
userstable (aliased asu) to thefriendstable (aliased asf) usingu.user_id = f.friend_user_id—this connects each friend's ID in the friends table to their full name in the users table. - SELECT: We only pull
first_nameandlast_namesince that's exactly what you need.
Extra Tips for Edge Cases
- If your tables have different names (e.g.,
user_profilesinstead ofusers), just replace the table names in the query to match your actual schema. - If your friendships are stored bidirectionally (e.g., both (John's ID, Friend's ID) and (Friend's ID, John's ID) exist in the friends table), add
DISTINCTto the SELECT to avoid duplicate results:SELECT DISTINCT u.first_name, u.last_name - If you want to include cases where a friend might not exist in the users table (unlikely, but possible), use
LEFT JOINinstead ofJOIN—though this would return NULLs for those missing entries.
内容的提问来源于stack exchange,提问作者robi10
相关产品推荐
相关产品推荐

