想象一下名为training_route
的表,其中包含多行,每行包含rowId
,gpsLocation
和athleteId
,请考虑以下因素:
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;
但我感到惭愧是迄今为止我提出的最好的,因为这是完全不可接受的性能。
答案 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
想法是