You should be able to combine to perform both queries in one. Your SQL will look like this:
SELECT U.username FROM users AS U INNER JOIN test_friends AS F ON U.Id = F.user_id WHERE F.friend_id = '{$userID}' AND F.active = 1 UNION SELECT u.username FROM users u INNER JOIN test_friends f ON u.id = f.user_id WHERE ( f.friend_id = '{$userID}' AND active = 1 ) OR ( f.user_id = '{$userID}' AND active = 1 )
It will also automatically delete duplicates, as if you included DISTINCT on the entire lot. (If you do not want this, you do "UNION ALL".)
Also, if you want to order the results, add βORDER BY 1 ASCβ at the end. You can only use the column numbers of the result set in the ORDER BY clause with union.
Union queries only work if the number and types of columns returned as a result given by each subquery are the same.
Beyond this: your first query appears to be a subset of the second query, so you really only need to complete the second query. I left it as a demonstration of how to make alliances, but in this case you really don't need to.
source share