- I have a feature to search for users on my website,
- I also have a feature for friends on my site.
- I have a query to search for the correct users on my site, and
- I have a query that determines the users that a user is friends with, they both work as they should,
so what i need assistance with is combining the two, to order friends before other users.
Search query:
SELECT userID, fname, lname,
FROM names
WHERE (
fname LIKE '".$term."%'
OR lname LIKE '".$term."%'
OR CONCAT(fname, ' ', lname) LIKE '".$term."%'
)
AND userID!=$session
ORDER BY fname ASC, lname ASC
LIMIT 10
Friends query:
SELECT CASE WHEN userID=$session
THEN userID2
ELSE userID
END AS friendID
FROM friends
WHERE (
userID=$session
OR userID2=$session
)
AND state='1'
so, a statement that would compare the two should be something like, IF names.userID=friends.friendID
Now I found a users suggestion for a similar issue on stackoverflow that seems like it would be a simple way of doing this, however I’m not entirely sure how to add it with my particular friends query, as it’s more of a complex query.
SELECT
posting.id,
IF(a.friend_id = b.criteria, 1, 0) AS is_friend
...
ORDER BY is_friend DESC, posting.id DESC
Use an outer join (left join) to join the user list returned by your first query with the friend list that your second query produces. Now you’ll be able to sort on the fact whether the second row set has a match: if it does, the corresponding row should go first.
This is an example of how you could implement the above:
The first sorting criterion,
(f.friendID IS NULL), evaluates tofalseif there’s a matchingfrow, i.e. if the user is a friend, and totrueotherwise. Consequently, sincefalsesorts beforetrue, the friends will be sorted before non-friends.