I have tables below:
user
+-----------------------------------------------+
| user_id | username | Password | ... |
+-----------------------------------------------+
| 1 | a | *** | ... |
+-----------------------------------------------+
| 2 | b | *** | ... |
+-----------------------------------------------+
| 3 | c | *** | ... |
+-----------------------------------------------+
| 4 | d | *** | ... |
+-----------------------------------------------+
| 5 | e | *** | ... |
+-----------------------------------------------+
friends
+-----------------------------------------------+
| f_id | user_id | friend_id | ... |
+-----------------------------------------------+
| 1 | 4 | 2 | ... |
+-----------------------------------------------+
| 2 | 4 | 1 | ... |
+-----------------------------------------------+
| 3 | 4 | 5 | ... |
+-----------------------------------------------+
| 4 | 4 | 3 | ... |
+-----------------------------------------------+
I want to get all users that are available to be added as friends (in this case, the user_id of 1 will have 3 more friends to be added (2, 3, 5). However, by using the following SQL statement below I only get 1 user (4) available to be added:
$sql = "SELECT * FROM user WHERE user.user_id NOT IN
(SELECT friends.friend_id FROM friends) AND
user.user_id <> $_SESSION['id']." ORDER BY RAND() LIMIT 5";
But this works great when I logged in as user 4 which there are no users available to be added. This is a bit tricky to me. Any idea would be very much appreciated.
Thanks
Edit:
How about this:
(in else clause use an invalid id or the same id as the logged in user)
http://sqlfiddle.com/#!2/12de1/62
One more way to solve this (but might not be an optimal solution):
Union query below might not be a costly query compared to complete join between two tables if number of friends an user has is less than total number of users in system.
Also don’t forget to add index on
uidandfidcolumn offriendstable.http://sqlfiddle.com/#!2/12de1/40