postgres find zip codes near specific zip code

﹥>﹥吖頭↗ 提交于 2019-12-22 08:16:01

问题


Assuming a Postgres Table containing zip as varchar(10) I want to get either all results matching a specific zip or extend my results with entries close to the queried one in case there are not enough results. Say:

A user searches for zip "56500" and my result-set returns 2 items running an exact match. In this case I want to perform a kind of like query that finds "565%" entries. Eventually I need to run this in one query.

Any suggestions?


回答1:


Something like this might be what you want:

SELECT …
FROM atable
WHERE zip = @zip

UNION ALL

SELECT …
FROM atable
WHERE NOT EXISTS (
  SELECT *
  FROM atable
  WHERE zip = @zip
)
  AND zip LIKE CONCAT(LEFT(@zip, 3), '%')

This may not be the most efficient solution, but at least it is a single query so might do well as a starting point.




回答2:


ORDER BY the delta from the desired zip?




回答3:


So, this is not specifically for PostgreSQL -- it was actually written for MySQL originally -- but it should work. I came across this article a while back that showed how to create a database containing zipcodes and latitude/longitude for each zipcode, then using trigonometry to calculate the distance between zip codes. Take a look at the link. I'm sure it will help you...

http://www.chrissibert.com/blog/2009/06/16/mysql-zip-codes-latitude-longitude-distance/



来源:https://stackoverflow.com/questions/8343673/postgres-find-zip-codes-near-specific-zip-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!