LEFT JOIN order and limit
Try replacing:
LEFT JOIN ps a ON a.account_id = fr.author
with:
LEFT JOIN ps a
ON a.PrimaryKey --- the Primary Key of ps
= ( SELECT b.PrimaryKey
FROM ps AS b
WHERE b.account_id = fr.author
ORDER BY b.level DESC
LIMIT 1
)
Replace the LEFT JOIN clause with something like:
...
LEFT JOIN (SELECT b.account_id, b.name
FROM (SELECT c.account_id, MAX(c.level) AS level
FROM ps AS c
GROUP BY c.account_id) AS d
JOIN ps AS b ON b.account_id = d.account_id AND b.level = d.level
) AS a
ON (a.account_id = fr.author)
...
This will still return multiple rows if there were several rows in ps
with the same account ID and the same level and that level was the maximum level:
NAME | LEVEL
Test1 | 1
Test2 | 120
Test3 | 2
Test4 | 1
Test5 | 120
If this situation can arise, then you have to decide what you want to do - and tune the query appropriately. For example, you might decide to use MAX(b.name)
with a GROUP BY clause to arbitrarily select the alphabetically later of the two names.