how to get distinct rows with max value

前端 未结 4 1720
萌比男神i
萌比男神i 2020-12-17 04:47

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

4条回答
  •  自闭症患者
    2020-12-17 05:50

    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.

提交回复
热议问题