I am working on this site that follow and unfollow users just like Twitter follow. The query below works then I notice it doesn’t show me users I don’t follow because the user has been followed by somebody or is following somebody
$stmt = $mysqli->prepare("SELECT * FROM town_users LEFT JOIN user_follow_list ON user_follow_list.following_id = town_users.user_id WHERE town_users.user_id != ? AND user_follow_list.follow_id IS NULL ORDER BY RAND() LIMIT 5"); $stmt->bind_param("i", $user_id);
Below is my table structure
town_users user_id username | 1 | ben | 2 | betty | 3 | tom | 4 | john user_follow_list follow_id follower_id following_id | 1 | 1 | 2 | 2 | 1 | 3
In the user_follow_list Ben
is following betty
and tom
. Now john
follows a user let say tom
,
follow_id follower_id following_id | 3 | 4 | 3
Now the problem am having is that john
doesn’t show up on ben
list of users to follow.
It’s meant to show users I haven’t followed so I can follow them.
Advertisement
Answer
SELECT * FROM town_users LEFT JOIN user_follow_list ON user_follow_list.follower_id = town_users.user_id WHERE town_users.user_id NOT IN (SELECT following_id FROM user_follow_list WHERE follower_id = 1) AND town_users.user_id != 1 GROUP BY town_users.user_id ORDER BY RAND() LIMIT 5
This query will get all the user that are not being followed by ($user_id = 1
).
$stmt = $mysqli->prepare("SELECT * FROM town_users LEFT JOIN user_follow_list ON user_follow_list.follower_id = town_users.user_id WHERE town_users.user_id NOT IN (SELECT following_id FROM user_follow_list WHERE follower_id = ?) AND town_users.user_id != ? GROUP BY town_users.user_id ORDER BY RAND() LIMIT 5"); $stmt->bind_param("ii", $user_id, $user_id);
Here’s a SQL Fiddle: http://sqlfiddle.com/#!9/96d55/23/0