2017-04-23 22 views
0

我在MySQL 5.7中有一個空間數據集,其中有列id:deviceid,latlng_point,time。 latlng_point是一個地理空間點。選擇MySQL中的下一個相關行

我想要實現的是計算距離點的距離。我不確定如何解決這個問題。

SELECT 
    ST_DISTANCE_SPHERE(latlng_point, i want the next latlng_point here) AS distance 
FROM points 
WHERE deviceid = 1 
ORDER BY time DESC; 

在PHP中我會做這樣的事情:

<?php 
    $conn = new mysqli($host,$user,$pass,$db); 

    $query = "SELECT latlng_point FROM points WHERE deviceid = 1..."; 

    $latlng_array = array();   
    if ($result = $conn->query($query)) { 
     while ($row = $result->fetch_assoc()) { 
      $latlng_array[] = $row; 
     } 
    } 

    $distance = 0; 
    for ($i = 0; $i < count($latlng_array) - 1; $i++) { 
     $pt1 = $latlng_array[$i]['latlng_point']; 
     $pt2 = $latlng_array[$i+1]['latlng_point']; 

     $distance += haversine_function($pt1,$pt2); 
    } 
    echo "Distance: {$distance}"; 
?> 

我試圖實現純在MySQL類似的東西。

+0

'next_latlng_point'應該是什麼? –

+0

這將是訂購時與deviceid相關的下一個latlng ...但我不確定如何處理。 – DigitalForce

+1

編輯你的問題,而不是在評論中回答,以使問題更清晰。你的桌子的模式是什麼?兩行如何相關?你是什​​麼意思_「下一個latlng與deviceid相關時,訂購」_? –

回答

0

試試這個:

SELECT SUM(ST_DISTANCE_SPHERE(p1.latlng_point, p2.latlng_point)) AS total_distance 
FROM points p1 
JOIN points p2 ON p2.id = (
    SELECT p.id 
    FROM points p 
    WHERE p.deviceid = p1.deviceid 
     AND p.time > p1.time 
    ORDER BY p.time ASC 
    LIMIT 1 
) 
WHERE p1.deviceid = 1 

(相關的)子查詢應返回的下一個點(按時間排序)的id

我不能告訴你它是否真的有效,或者它甚至可以工作(不能測試它)。

但是,您應該有一個索引(deviceid, time) - 假設id是主鍵。