How can I select only the first distinct match from a field in MySQL?

后端 未结 5 1662
终归单人心
终归单人心 2021-01-14 22:49

How can I only return the first distinct match of a field in MySQL?

My Table:

name     hash
----------------
Anna     ABC
Barb     DEF
Charlie  GHI
A         


        
5条回答
  •  日久生厌
    2021-01-14 23:19

    When using GROUP BY, MySQL destroy the desc order on the same query level.

    Instead of:

    SELECT name, hash 
    FROM my_table
    GROUP BY name
    ORDER BY name ASC, hash DESC
    

    Use sub query on descending order:

    SELECT * FROM(
      SELECT name, hash
      FROM my_table
      ORDER BY name ASC, hash DESC
    )Q 
    GROUP BY name
    

提交回复
热议问题