Skip to content
Advertisement

Select records within 5 kilometers with group by

I have an application that uses coordinates. I want to select records within 5 km that were thrown in the last 5 minutes. How can I do this easiest? I want to write a procedure. The values I will send to the procedure are latitude (float 11,8) and longitude (float 11,8).

Example table:

id   car_id   lati   longi   created_at
1      15      xx      yy    2021-04-19 12:00:00
2      16      xx      yy    2021-04-19 13:00:00
3      15      xx      yy    2021-04-19 15:00:00

I found a query like this but can’t use group by.

SELECT *, ( 3959 * acos( cos( radians("xx.xxx") ) * cos( radians( lati ) ) * cos( radians( longi ) - radians("yy.yyy") ) + sin( radians("xx.xxx") ) * sin( radians( lati ) ) ) ) AS distance 
FROM mobil_gps 
where created_at >= DATE_SUB(NOW(),INTERVAL 5 minute)
HAVING distance < 5;

EDIT:

For example. I am a customer and want to see the locations of vehicles within 5 km.

Advertisement

Answer

You can use ST_DISTANCE_SPHERE to calculate the distance between two points that are on a sphere.

The example from the MariaDB KB:

SET @zenica   = ST_GeomFromText('POINT(17.907743 44.203438)');
SET @sarajevo = ST_GeomFromText('POINT(18.413076 43.856258)');
SELECT ST_Distance_Sphere(@zenica, @sarajevo);

55878.59337591705

If you’re interested in the distance on a plane, use ST_DISTANCE.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement