SELECT sqrt(pow(inputxvalue - fieldx,2) +(pow(inputyvalue - fieldy,2)) AS Distance FROM tablename ORDER BY Distance LIMIT
WHERE xcol between (inputx - theshold) and (inputx + theshold) AND ycol between (inputy - theshold) and (inputy + theshold)
In software engineering terms, the "big O notation" of a query on the closest distance from any
single point is inherently "O(N)" [the effort required to solve the problem is proprtional to the
number of rows in the table -- aka, full table scan].
The only to way to reduce processing is to put a limit on the magnitude of the distance by
indexing both X and Y ("CREATE INDEX foo ON table(xcol,ycol)") and adding a WHERE
clause to the query:WHERE xcol between (inputx - theshold) and (inputx + theshold) AND ycol between (inputy - theshold) and (inputy + theshold)
This is, in essence, what you're losing by not being able to generate a buffer about the search
point and use the spatial index to limit return results [an unbounded query on a spatial relationship
of distance(inputpt,ptcol) would also be O(N)].
- V
Hi
If you have the freedom to alter the schema of your table you could implement a geohash-based query:
http://code.google.com/p/python-geohash/
You would need to calculate a hash onto each point, with a precision to suit your data.
Then your nearby query would devolve into a string range query.
Regards