I'm unclear on the specifics, but I am pretty sure it takes two steps:
- Find the rows that match the "active", "distance quota", and "15 to 1 minute ago". See the Comment where I asked for specifics.
- Find the latest of each. This involves a "groupwise max" algorithm; see the tag I added.
Then put the two pieces together. MySQL 8.0 has CTEs, which would make it easier. But, since you are on 5.7, it gets messier
CREATE TEMPORARY TABLE t
SELECT ... ((step 1));
Then apply the group-wise max to t
.
If you have thousands of rows, optimization will be a problem. This is because the distance calc is slow. We can discuss that after you get the code working [slowly] with the groupwise-max.
If you will have millions of rows and the resolution needed is only enough to distinguish two trucks, see this for picking something less bulky than DOUBLE
(8 bytes each) for lat and lng: http://mysql.rjweb.org/doc.php/latlng#representation_choices