[RESOLVED] Location Query
I have a complicated query that I'd like some advice on. The ultimate goal is to find the waypoint in a table that is closest to some lat/lon that are supplied.
The closest would be minimizing the distance using the Haversine formula, which is straightforward. But that distance isn't the ultimate goal. The waypoints may or may not be used in a survey, and I want only the ones that ARE used in the survey, and the return is a field from that survey. From there, it gets a bit worse.
The survey is table S, which has two child tables A and B. The waypoints, if they tie to anything, tie to either A or B, or one of two fields in the Survey S.1 or S.2.
In code I do (something like) this by getting all the waypoints that join to A, then getting all the waypoints that join to B, then adding in any waypoints that join to S.1 or S.2. That would get me the set of all waypoints that are used by that survey.
In SQL, I could do the same thing with a UNION query to get all the waypoints that join to any A, and all the waypoints that join to any B, and all the waypoints that join to any S.1 and all the waypoints that join to any S.2. That UNION could have the lat/lon of the waypoint along with the one field from S that needs to be returned, which I'll call S.X.
From that UNION, I would then be getting the S.X with the minimum distance from the target lat/lon.
That all seems viable, but it doesn't seem particularly efficient, so I figured I'd ask for a solution that would potentially avoid the UNION, which would really be the UNION of three sub queries. Is there a better way?
Re: [RESOLVED] Location Query
As a last option:
read this thread: https://microsoft.public.sqlserver.s...ndexing-floats
and think about maybe putting an index on your value columns
Re: [RESOLVED] Location Query
This is a GIS problem. SQL Server actually supports Geography spatial types, which allows for geographical spatial math (like distance) on those coordinates.