You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 like user_id (unique identifier), first_name, last_name, and other user-specific info.
  • Friends table (let's call it friends): Tracks friendships with columns user_id (the main user) and friend_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 unique user_id for John Doe—this is how we link him to his friends in the friends table.
  • JOIN: We join the users table (aliased as u) to the friends table (aliased as f) using u.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_name and last_name since that's exactly what you need.

Extra Tips for Edge Cases

  • If your tables have different names (e.g., user_profiles instead of users), 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 DISTINCT to 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 JOIN instead of JOIN—though this would return NULLs for those missing entries.

内容的提问来源于stack exchange,提问作者robi10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:35:02