Ok, so im working out a search function for MySQL but have come across something I can’t seem to work out. I am trying to make a script to search the users friends, and return the friends with a better score. This is what I have so far:
SELECT id, first_name, last_name, image_id FROM users
WHERE id IN (
SELECT receiver AS friend FROM friends WHERE initiator = :me AND status = :status
UNION
SELECT initiator AS friend FROM friends WHERE receiver = :me AND status = :status
) ORDER BY score AND concat(first_name, ' ', last_name) LIKE '%test query%';
Now everything works till I try and order the friends by Score. Can anyone workout how to order the friends by score? If you need me to clarify anything just ask.
I have the following two tables.
Users Table: 
Friends Table:
As requested here is some sample data:
As an example, I have three users:
ID: 1, first_name: Michael, last_name: Sample
ID: 2, first_name: John, last_name: Citizen
ID: 3, first_name: Caitlin, last_name: Wired
The first entry below will make Michael and Caitlin be friends by showing that Michael initiated a friend request and Caitlin (the receiver) accepted it. (Hence the status of 1) their base score is 10. The second entry shows that John is also friends with Caitlin (initiated by Caitlin) but have a better score.
ID: 10000, initiator: 1, receiver: 3, status: 1, score: 10
ID: 10001, initiator: 3, receiver: 2, status: 1, score: 20
So in the case of this sample data. If Caitlin was the user searching for her friends, it should show John than Michael.
The outer statement selects only from the
userscolumn, which doesn’t have ascorecolumn. Just about any statement using sub-selects can (and should) be re-written using joins. In this particular case, it will allow all thefriendsfields to be used in the clauses.The expressions used in the
WHEREclauses of the sub-selects become the join condition. A union is in a sense equivalent toOR(both are basically conjunctions).The rest of the statement pretty much remains as it is.
All together, that’s:
Note that this is untested, and just off the top of my head.