好友系统单查询实现:关联用户表展示好友及请求用户名
Single SQL Query to Fetch Friends & Pending Requests with Usernames
Got it, let's tackle this problem. You want a single SQL query to pull both your confirmed friends and pending friend requests, while correctly showing the other user's username—here's how to do it right:
-- Replace @current_user_id with the logged-in user's actual ID (e.g., $_SESSION['user_id'] in PHP) SELECT -- Get the other user's ID, regardless of whether we sent or received the request CASE WHEN f.user_id = @current_user_id THEN f.friend_id ELSE f.user_id END AS other_user_id, -- Pull the other user's username by joining on the unified ID u.user_name AS other_user_name, -- Label the relationship status for easy display CASE WHEN f.confirmed = 1 THEN 'Confirmed Friend' WHEN f.user_id = @current_user_id THEN 'Pending Request Sent' ELSE 'Pending Request Received' END AS relationship_status, -- Optional: Keep original fields if you need to handle actions (like accepting requests) f.user_id AS request_sender_id, f.friend_id AS request_receiver_id, f.confirmed FROM friends f -- Join the users table to get the other user's name LEFT JOIN users u ON u.user_id = CASE WHEN f.user_id = @current_user_id THEN f.friend_id ELSE f.user_id END -- Filter only relationships involving the current user WHERE f.user_id = @current_user_id OR f.friend_id = @current_user_id -- Optional: Sort by status and username for cleaner results ORDER BY relationship_status, other_user_name;
How This Works:
- Unified Other User ID: The first
CASEexpression normalizes the "other user" ID—whether you sent the request (so the other person isfriend_id) or received it (so the other person isuser_id). This lets us join theuserstable once to get the username, no messy multiple joins or subqueries. - Clear Status Labels: The second
CASEmakes it easy to display what type of relationship each row is, so your frontend can show "Confirmed Friends" separately from pending sent/received requests. - Efficient Filtering: The
WHEREclause only pulls rows that involve the current user, so you don't get irrelevant data.
Pro Tips:
- Add indexes on
friends.user_idandfriends.friend_id—this will speed up the query significantly as your user base grows. - If you only want to show confirmed friends, add
AND f.confirmed = 1to theWHEREclause. - If you need to exclude sent requests that haven't been accepted, adjust the
WHEREorCASElogic as needed.
内容的提问来源于stack exchange,提问作者Matic Jan
相关产品推荐
相关产品推荐

