像这样的东西。按顺序生成2个位置列表,并添加序列号,并根据车辆id和序列号连续加入。然后进行计算。
SELECT Sub1.id, Sub1.vehicle_id, ACOS(SIN( Sub1.lat * PI) * SIN(Sub2.lat * PI) + COS( Sub1.lat * PI) * COS(Sub2.lat * PI) * COS(( Sub1.lon - Sub2.lon ) * PI)) / PI * 60 * 1.1515 AS distance
FROM
(
SELECT id, vehicle_id, longitude, lattitude, @seq:=IF(@prev_vehicle_id=vehicle_id, 1, @seq) + 1 AS seq, @prev_vehicle_id := vehicle_id
FROM
(
SELECT id, vehicle_id, longitude, lattitude
FROM markers
ORDER BY vehicle_id, id
) Sub3
CROSS JOIN (SELECT @seq:=1, @prev_vehicle_id:=0
) Sub1
INNER JOIN
(
SELECT id, vehicle_id, longitude, lattitude, @seq1:=IF(@prev_vehicle_id1=vehicle_id, 0, @seq1) + 1 AS seq, @prev_vehicle_id1 := vehicle_id
FROM
(
SELECT id, vehicle_id, longitude, lattitude
FROM markers
ORDER BY vehicle_id, id
) Sub4
CROSS JOIN (SELECT @seq1:=0, @prev_vehicle_id1:=0
) Sub2
ON Sub1.vehicle_id = Sub2.vehicle_id
AND Sub1.seq = Sub2.seq