>> I currently have a table, ZipCodes, with standard columns of City,

State, Latitude, Longitude ... user inputs a city and state I return

the zip codes within that city and state AND the zip codes of the (n)

nearest cities. <<

Notice that you do not need the exact distance, so the spherical trig

is over kill. You can pretend the world is flat and still get the

answer. Let me assume that we have (x, y) co-ordinates.

SELECT my_city, my_state, Destinations.city, Destinations.state,

MIN(S1.seq) AS radius

FROM (SELECT *

FROM Zipcodes

WHERE city = my_city

AND state = my_state) AS Origins (x,y)

CROSS JOIN

(SELECT *

FROM Zipcodes

WHERE city <> my_city

OR state <> my_state) AS Destinations (x,y)

CROSS JOIN

Sequence AS S1

WHERE SQRT (SQR(Origins.x - Destinations.x) + SQR(Origins.y -

Destinations.y))

<= S1.seq

AND S1.seq <= <<limit>>

GROUP BY my_city, my_state, Destinations.city, Destinations.state;

The Sequence table is a standard programming trick; it is a list of

integers from 1 to (n). The Origins table is where we start, all the

zip codes in my city. The Destinaitons table is where we finish and

radius is how far away they are. The constant <<limit>> is some upper

limit on distance.

You can now prune this down with a "GROUP BY radius HAVING COUNT(*) =

??" or by adjusting <<limit>>.

## Bookmarks