选择MySQL中的下一个相关行

时间:2017-04-23 17:43:12

标签: mysql sql

我在MySQL 5.7中有一个空间数据集,我有列:id,deviceid,latlng_point,time。 latlng_point是一个地理空间点。

我想要实现的是计算距离点的距离。我不确定如何处理这个问题。

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中实现类似的东西。

1 个答案:

答案 0 :(得分: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是主键。