php - MySQL query with DISTINCT keyword -


my mysql table country_phone_codes looks this

id     country_code     area_code     name ------------------------------------------------------------ 1   |   93           |  93         |  afghanistan 2   |   93           |  9370       |  afghanistan - mobile 3   |   93           |  9375       |  afghanistan - mobile 4   |   355          |  355        |  albania 5   |   355          |  35568      |  albania - mobile - amc 6   |   213          |  213        |  algeria 7   |   213          |  2131       |  algeria - cat ------------------------------------------------------------ 

these few records of more 28000 records. trying formulate query provide me result this-

country_code    name ----------------------------- 93            |  afghanistan 355           |  albania 213           |  algeria ----------------------------- 

by using select distinct(country_code) country_phone_codes order country_code limit 0,260, able distinct country codes. how corresponding country name?

the answer trivial, using group by:

select country_code,min(name) country_phone_codes group country_code; 

the distinct function , order by aren’t necessary group by. original question pertained mysql, min() aggregate function isn’t necessary , might see better performance without if of following true:

  • the server mysql
  • the storage engine innodb
  • the first column of example data primary key , entries follow same ordering suggested small sample, namely, country name appears before other names in group.

this works because innodb storage engine scan in order of primary key and, nonaggregated columns, use first value finds.


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -