2014-11-04 89 views
1

試想一個表稱爲training_route其中包含幾個行,每行有一個rowIdgpsLocationathleteId並考慮以下因素:同一行中提取MIN和MAX

  • 最低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   ... 

我想什麼有是由非常相同的查詢由athleteId分組,同樣的行中的每個路徑的第一個和最後的位置:

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; 

但我很慚愧,是我想出來的,到目前爲止,因爲它是完全不可接受的性能比較明智的最好的。

回答

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的每個運動員
  • 與表再次加入之前的結果得到gpscoörodinatesmin min rowid
  • 並再次與原始表加入以獲取gpscoörodi納茨爲最大的rowid
+0

我想類似的東西,但即使不知道,你可以從聲明中做的「主查詢」,也救了我的夜晚,謝謝! – Rikard 2014-11-04 22:41:25

+0

@Rikard - 不客氣。這是一個很好的結構,因爲它適用於大多數(如果不是全部的話)DBMS。它肯定會在稍後派上用場。 – 2014-11-04 22:46:39