SQL Group By and min (MySQL)

前端 未结 3 1784
挽巷
挽巷 2020-12-07 01:41

I have the following SQL:

select code, distance from places;    

The output is below:

CODE    DISTANCE            LOCATION
         


        
3条回答
  •  时光说笑
    2020-12-07 02:29

    To get the correct associated location, you'll need to join a subselect which gets the minimum distance per code on the condition that the distance in the outer main table matches with the minimum distance derived in the subselect.

    SELECT a.code, a.distance
    FROM   places a
    INNER JOIN
    (
        SELECT   code, MIN(distance) AS mindistance
        FROM     places
        GROUP BY code
    ) b ON a.code = b.code AND a.distance = b.mindistance
    ORDER BY a.distance
    

提交回复
热议问题