Edit:
How about this: (in else clause use an invalid id or the same id as the logged in user)
select * from users where id not in
(
select (
case
when uid = 1 then id
when fid = 1 then uid
else 0
end
) from friends where uid = 1 or fid = 1
) and id != 1 order by rand() limit 5;
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 uid
and fid
column of friends
table.
select * from users where id not in
(
select id from friends where uid = 1
union
select uid from friends where fid = 1
) and id != 1 order by rand() limit 5;