MySQL: Select N rows, but with only unique values in one column

前端 未结 5 796
醉梦人生
醉梦人生 2020-12-23 10:07

Given this data set:

ID  Name            City            Birthyear
1   Egon Spengler   New York        1957
2   Mac Taylor      New York        1955
3   Sara         


        
5条回答
  •  北海茫月
    2020-12-23 10:25

    Probably not the most elegant of solutions, and the performance of IN may suffer on larger tables.

    The nested query gets the minimum Birthyear for each city. Only records who have this Birthyear are matched in the outer query. Ordering by age then limiting to 3 results gets you the 3 oldest people who are also the oldest in their city (Egon Spengler drops out..)

    SELECT Name, City, Birthyear, COUNT(*) AS ct
    FROM table
    WHERE Birthyear IN (SELECT MIN(Birthyear)
                   FROM table
                   GROUP by City)
    GROUP BY City
    ORDER BY Birthyear DESC LIMIT 3;
    
    +-----------------+-------------+------+----+
    | name            | city        | year | ct |
    +-----------------+-------------+------+----+
    | Henry Jones     | Chicago     | 1899 | 1  |
    | Mac Taylor      | New York    | 1955 | 1  |
    | Sarah Connor    | Los Angeles | 1959 | 1  |
    +-----------------+-------------+------+----+
    

    Edit - added GROUP BY City to outer query, as people with same birth years would return multiple values. Grouping on the outer query ensures that only one result will be returned per city, if more than one person has that minimum Birthyear. The ct column will show if more than one person exists in the city with that Birthyear

提交回复
热议问题