Search code examples
sqlsqliterequestgeographygis

SQLite : finding a function's minimum values


I have those tables

Node (#id, route_id, lat, lng)

Route(#id)

And I have four input values : $lat1, $lng1, $lat2, $lng2, which represent 2 GPS coordinates GPS1 and GPS2. I also have a distance function that I added to the database : distance( lat1, lng1, lat2, lng2)

What I am looking for is the request that will give me the closest point to GPS1, and the closest point to GPS2 for each route. So I guess it should start like :

SELECT r.id, n1.lat, n1.lng, n2.lat, n2.lng
FROM Node n1, Node n2
JOIN Route r ON n1.route_id = r.id AND n2.route_id = r.id

And I tried to add

WHERE distance(n1.lat,n1.lng,$lat1,$lng1) = MIN (distance(n1.lat,n1.lng,$lat1,$lng1))
AND distance(n2.lat,n2.lng,$lat2,$lng2) = MIN (distance(n2.lat,n2.lng,$lat2,$lng2))

But it throws this error :

"misuse of aggregate function MIN()"

I also thought I could use

SELECT r.id, n1.lat, n1.lng, n2.lat, n2.lng, distance(n1.lat,n1.lng,$lat1,$lng1) AS d1, distance(n2.lat,n2.lng,$lat2,$lng2) AS d2
FROM Node n1, Node n2
JOIN Route r ON n1.route_id = r.id AND n2.route_id = r.id
GROUP BY r.id

And to sort it by d1 for the n1.lat, n1.lng, d1 columns and by d2 for the n2.lat, n2.lng, d2 columns but I don't know how to do that.

Any idea ?


Solution

  • You need to perform a correlated query:

    SELECT r.id, n1.lat, n1.lng, n2.lat, n2.lng
    FROM Node n1, Node n2
    JOIN Route r ON n1.route_id = r.id AND n2.route_id = r.id
    WHERE distance(n1.lat,n1.lng,$lat1,$lng1) = (
                                                 SELECT MIN (distance(lat,lng,$lat1,$lng1))
                                                 FROM Node c_n
                                                 WHERE c_n.nid = n1.nid)
    AND distance(n2.lat,n2.lng,$lat2,$lng2) = (
                                                 SELECT MIN (distance(lat,lng,$lat1,$lng1))
                                                 FROM Node c_n
                                                 WHERE c_n.nid = n2.nid)
    

    (At this conjecture I am unable to test this, please forgive me if this is not exact, but it should be close. I will check up on this later.)