my apologies for asking what must be very simple to solve, but I just can\'t seem to wrap my mind around this.. I couldn\'t even come up with a really fitting title for my q
SELECT id, authorId, answer, votes
FROM ( SELECT id, authorId, answer, votes
FROM answers
ORDER BY votes DESC) AS h
GROUP BY authorId
This little neat trick is built basing on GROUP BY
to retrieve the first row of each case. Usually this is by default ORDER BY id ASC
, but through this sub query, the first row in each authorId
with the highest votes
.
Note: As mentioned by Iain Elder, this solution doesn't work with ONLY_FULL_GROUP_BY
active and only works in MySQL. This solution is to a certain extent unsupported due to lack of documentation confirming this behavior. It works well for me and has always worked well for me however.
This method still works on the latest MySQL on sqlfiddle.