问题
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