My MySQL table country_phone_codes looks something like this
id country_code area_code name
---------------------------------------------------------
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:
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.