Created
November 24, 2010 19:16
-
-
Save anotheremily/714212 to your computer and use it in GitHub Desktop.
Get nearby zip codes from a certain zip code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- I think I fixed all of the bugs, but there may be one. | |
-- Now I just need to see about some optimization | |
SELECT | |
n.city, | |
n.zip_code, | |
n.latitude, | |
n.longitude, | |
3958.75587 * c AS distance | |
FROM ( | |
SELECT | |
n.city, | |
n.zip_code, | |
n.latitude, | |
n.longitude, | |
2 * ATAN2( SQRT( n.a ), SQRT( 1 - n.a ) ) AS c | |
FROM ( | |
SELECT | |
n.city, | |
n.zip_code, | |
n.latitude, | |
n.longitude, | |
SIN( n.dLat / 2 ) * SIN( n.dLat / 2 ) | |
+ COS( n.nRadLng ) * COS( n.oRadLng ) | |
* SIN( dLng/2 ) * SIN( dLng/2 ) AS a | |
FROM ( | |
SELECT | |
n.city, | |
n.zip_code, | |
n.latitude, | |
n.longitude, | |
RADIANS( n.latitude - o.latitude ) AS dLat, | |
RADIANS( n.longitude - o.longitude ) AS dLng, | |
o.latitude, | |
o.longitude, | |
RADIANS( o.latitude ) AS oRadLat, | |
RADIANS( o.longitude ) AS oRadLng, | |
RADIANS( n.latitude ) AS nRadLat, | |
RADIANS( n.longitude ) AS nRadLng | |
FROM | |
iws_zip_codes n, | |
( | |
SELECT | |
o.latitude, | |
o.longitude, | |
o.latRange, | |
o.lngRange, | |
o.latitude - o.latRange AS minLat, | |
o.latitude + o.latRange AS maxLat, | |
o.longitude - o.lngRange AS minLng, | |
o.longitude + o.lngRange AS maxLng | |
FROM ( | |
SELECT | |
o.latitude, | |
o.longitude, | |
5/69.172 AS latRange, | |
ABS( 5 / ( COS( o.longitude ) * 69.172 ) ) AS lngRange | |
FROM iws_zip_codes o | |
WHERE o.zip_code = 23505 | |
) o | |
) o | |
WHERE n.latitude BETWEEN o.minLat AND o.maxLat | |
AND n.longitude BETWEEN o.minLng AND o.maxLng | |
) n | |
) n | |
) n; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment