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

后端 未结 5 1650
终归单人心
终归单人心 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:11

    DISTINCT does not work that way, the values must be distinct across all columns being returned.

    You can always use an aggregate function on the hash function and GROUP BY name which will return one hash value for each name:

    SELECT name, min(hash) hash
    FROM my_table 
    WHERE name LIKE '%An%' 
    GROUP BY name;
    

    See SQL Fiddle with Demo.

    Note: using the aggregate function with the GROUP BY will make sure that you will always return the expected value for the hash column. When you do not GROUP BY or aggregate the items in the SELECT list, you might return unexpected results. (see MySQL Extensions to GROUP BY)

    From the MySQL Docs:

    MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. ... You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. Sorting of the result set occurs after values have been chosen, and ORDER BY does not affect which values the server chooses.

提交回复
热议问题