MySQL query with DISTINCT keyword

后端 未结 5 814
醉酒成梦
醉酒成梦 2021-01-24 05:23

My MySQL table country_phone_codes looks something like this

id     country_code     area_code     name
---------------------------------------------------------         


        
5条回答
  •  粉色の甜心
    2021-01-24 05:40

    The answer is trivial, using GROUP BY:

    SELECT country_code,MIN(name)
    FROM country_phone_codes
    GROUP BY country_code;
    

    The DISTINCT function and ORDER BY aren’t necessary with GROUP BY. As the original question specifically pertained to MySQL, the MIN() aggregate function isn’t necessary and you might see better performance without it if all of the following are true:

    • The server is MySQL
    • The storage engine is InnoDB
    • The first column of the example data is the primary key and the entries follow the same ordering suggested by the small sample, namely, the country name appears before all other names in the group.

    This works because the InnoDB storage engine will scan in the order of the primary key and, for nonaggregated columns, it will use the first value it finds.

提交回复
热议问题