SQL/mysql - Select distinct/UNIQUE but return all columns?

前端 未结 18 1092
忘掉有多难
忘掉有多难 2020-11-22 12:08
SELECT DISTINCT field1, field2, field3, ......   FROM table

I am trying to accomplish the following sql statement but I want it to return all colum

18条回答
  •  春和景丽
    2020-11-22 12:15

    That's a really good question. I have read some useful answers here already, but probably I can add a more precise explanation.

    Reducing the number of query results with a GROUP BY statement is easy as long as you don't query additional information. Let's assume you got the following table 'locations'.

    --country-- --city--
     France      Lyon
     Poland      Krakow
     France      Paris
     France      Marseille
     Italy       Milano
    

    Now the query

    SELECT country FROM locations
    GROUP BY country
    

    will result in:

    --country--
     France
     Poland
     Italy
    

    However, the following query

    SELECT country, city FROM locations
    GROUP BY country
    

    ...throws an error in MS SQL, because how could your computer know which of the three French cities "Lyon", "Paris" or "Marseille" you want to read in the field to the right of "France"?

    In order to correct the second query, you must add this information. One way to do this is to use the functions MAX() or MIN(), selecting the biggest or smallest value among all candidates. MAX() and MIN() are not only applicable to numeric values, but also compare the alphabetical order of string values.

    SELECT country, MAX(city) FROM locations
    GROUP BY country
    

    will result in:

    --country-- --city--
     France      Paris
     Poland      Krakow
     Italy       Milano
    

    or:

    SELECT country, MIN(city) FROM locations
    GROUP BY country
    

    will result in:

    --country-- --city--
     France      Lyon
     Poland      Krakow
     Italy       Milano
    

    These functions are a good solution as long as you are fine with selecting your value from the either ends of the alphabetical (or numeric) order. But what if this is not the case? Let us assume that you need a value with a certain characteristic, e.g. starting with the letter 'M'. Now things get complicated.

    The only solution I could find so far is to put your whole query into a subquery, and to construct the additional column outside of it by hands:

    SELECT
         countrylist.*,
         (SELECT TOP 1 city
         FROM locations
         WHERE
              country = countrylist.country
              AND city like 'M%'
         )
    FROM
    (SELECT country FROM locations
    GROUP BY country) countrylist
    

    will result in:

    --country-- --city--
     France      Marseille
     Poland      NULL
     Italy       Milano
    

提交回复
热议问题