MySQL query with DISTINCT keyword

后端 未结 5 811
醉酒成梦
醉酒成梦 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:52

    Seems like you have a one-to-many relationship between country_code and name.

    If you do a simple GROUP BY query like

    SELECT country_code,name FROM country_phone_codes GROUP BY country_code
    

    you might end up with

    country_code    name
    -----------------------------
    93            |  AFGHANISTAN
    355           |  ALBANIA
    213           |  ALGERIA
    124           |  COUNTRY - MOBILE
    -----------------------------
    

    assuming all your country names are

    COUNTRY
    COUNTRY - SOMETHING
    COUNTRY - SOMETHING - SOMETHING
    

    would be better to use

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

    so you end up with

    country_code    name
    -----------------------------
    93            |  AFGHANISTAN
    355           |  ALBANIA
    213           |  ALGERIA
    xxx           |  COUNTRY
    -----------------------------
    

    this is assuming that you have both of those records in your table

    id     country_code     area_code     name
    ------------------------------------------------------------
    xx   |   xxx          |  xx        |  COUNTRY
    xx   |   xxx          |  xx        |  COUNTRY - SOMETHING
    ------------------------------------------------------------
    

提交回复
热议问题