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

SQL查询语句扩展需求:获取指定用户及其关注用户的帖子

Extend SQL Query to Include Posts from Followed Users

Got it, let's fix this query to show both the target user's posts and posts from everyone they follow. First, I'll assume you have a table tracking follow relationships—let's call it Followers (a standard name for this use case) with two key columns:

  • FollowerID: The ID of the user who's following someone
  • FollowingID: The ID of the user being followed

If your follow table uses different names (like Followings, or columns like FollowerUserID), just adjust the examples below to match your actual schema.

Option 1: Use an IN Subquery (Intuitive & Readable)

This approach first collects all relevant user IDs (the target user + their followed users) using a UNION, then filters posts to only those users:

SELECT Posts.*, Profiles.ProfilePhoto, Users.Name, Users.Username
FROM Posts
INNER JOIN Profiles ON Posts.UserID = Profiles.UserID
INNER JOIN Users ON Posts.UserID = Users.ID
WHERE Posts.UserID IN (
    -- Include the target user themselves
    SELECT ?
    UNION
    -- Add all users the target user follows
    SELECT FollowingID
    FROM Followers
    WHERE FollowerID = ?
)
ORDER BY Posts.CreateDate DESC;

How this works:

  • The subquery inside IN combines two sets: the target user's ID (from the ? parameter) and all FollowingIDs where the FollowerID matches the target user.
  • UNION automatically removes duplicate IDs (in case the user somehow follows themselves, though you should prevent that in your app logic).
  • We keep your original INNER JOINs to pull in profile photos and user details—this assumes every user has a profile entry (if not, switch to LEFT JOIN to avoid missing posts).

Option 2: Use a JOIN (Better for Large Datasets)

If you're working with a lot of data, a JOIN-based approach can be more performant than a subquery. Here we create a temporary "relevant users" table first, then join it to Posts:

SELECT Posts.*, Profiles.ProfilePhoto, Users.Name, Users.Username
FROM Posts
INNER JOIN Profiles ON Posts.UserID = Profiles.UserID
INNER JOIN Users ON Posts.UserID = Users.ID
-- Join with our list of relevant users (target + followed)
INNER JOIN (
    SELECT ? AS UserID
    UNION
    SELECT FollowingID AS UserID
    FROM Followers
    WHERE FollowerID = ?
) AS RelevantUsers ON Posts.UserID = RelevantUsers.UserID
ORDER BY Posts.CreateDate DESC;

Performance Tip:

If you know your Followers table has no duplicate follow entries (e.g., you enforce a unique constraint on (FollowerID, FollowingID)), replace UNION with UNION ALL. This skips the duplicate-check step and speeds up the query.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:13:13