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

前端 未结 5 812
醉梦人生
醉梦人生 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:17

    @BlaM

    UPDATED just found that its good to use USING instead of ON. it will remove duplicate columns in result.

    SELECT P.*, COUNT(*) AS ct
       FROM people P
       JOIN (SELECT City, MIN(Birthyear) AS Birthyear
                  FROM people 
                  GROUP by City) P2 USING(Birthyear, City)
       GROUP BY P.City
       ORDER BY P.Birthyear ASC 
       LIMIT 10;
    

    ORIGINAL POST

    hi, i've tried to use your updated query but i was getting wrong results until i've added extra condition to join (also extra column into join select). transfered to your query, i'am using this:

    SELECT P.*, COUNT(*) AS ct
       FROM people P
       JOIN (SELECT City, MIN(Birthyear) AS Birthyear
                  FROM people 
                  GROUP by City) P2 ON P2.Birthyear = P.Birthyear AND P2.City = P.City
       GROUP BY P.City
       ORDER BY P.Birthyear ASC 
       LIMIT 10;
    

    in theory you should not need last GROUP BY P.City, but i've left it there for now, just in case. will probably remove it later.

提交回复
热议问题