在同一行中获取MIN和MAX

时间:2014-11-04 22:11:35

标签: mysql max min

想象一下名为training_route的表,其中包含多行,每行包含rowIdgpsLocationathleteId,请考虑以下因素:

  • 最低rowId定义第一个位置,最大rowId定义最后一个位置
  • 所有行一起定义了相关运动员的路线

实施例

rowId   athleteId   gpsLocation
100       1           "40.7127837,-74.00594130000002" <- first location for athlete #1
101       1           "41.1234872,-71.41300000022342"
102       1           "42.1234872,-69.23112200022342" <- last location for athlete #1
103       2           "39.5993499,-74.00594130000002" <- first location for athlete #2
104       2           "38.9093885,-73.31300000022342"
106       2           "37.1234872,-63.34215200022342" <- last location for athlete #2
107       3           ...

我想要的是每个路线的第一个和最后一个位置,由AthleId分组,在同一行中由同一个查询:

athleteId   firstLocation                       lastLocation
1           "40.7127837,-74.00594130000002"     "42.1234872,-69.23112200022342"
2           "39.5993499,-74.00594130000002"     "37.1234872,-63.34215200022342"
3           ...             ...

MySQL查询怎么样?

P.S。

我尝试过这样的事情:

SELECT training_route.athleteId,
       ( SELECT training_route.gpsLocation FROM training_route WHERE training_route.athleteId = route.athleteId ORDER BY training_route.rowId ASC  LIMIT 1 ) AS firstLocation,
       ( SELECT training_route.gpsLocation FROM training_route WHERE training_route.athleteId = route.athleteId ORDER BY training_route.rowId DESC LIMIT 1 ) AS lastLocation,
FROM   training_route AS route
WHERE  training_route.athleteId IN ( 1, 2, 3 ) GROUP BY training_route.athleteId;

但我感到惭愧是迄今为止我提出的最好的,因为这是完全不可接受的性能。

1 个答案:

答案 0 :(得分:3)

以下应该使用mysql

SELECT *
FROM   (
        SELECT MIN(rowid) minrowid
               , MAX(rowid) maxrowid
               , athleteid
        FROM  training_route
        GROUP BY
              athleteid
       ) minmax
       INNER JOIN training_route trmin ON trmin.athleteid = minmax.athleteid 
                                          AND trmin.minrowid = minmax.rowid
       INNER JOIN training_route trmax ON trmax.athleteid = minmax.athleteid 
                                          AND trmax.maxrowid = minmax.rowid

想法是

  • 获得每位运动员的最小和最大rowid
  • 再次使用表格加入之前的结果,以获取min rowid的gpscoörodinates
  • 并再次加入原始表格以获取max rowid
  • 的gpscoörodinates