I’m working in MySQL with PHP. I’m doing a query for a zip code from one table which contains the zip codes and the lat/lon for each zip code. The second table contains the zip code and average income for that zip code. The user gives a zip code (let’s call this the base zip code) and it returns a 15 mile radius of zip codes. Via the web page the user can query with a range of incomes that uses a BETWEEN for MySQL in PHP.
My problem is, depending on what range the user selects, their base zip code might not appear all the time because it’s outside of the income ranges. When this happens it is confusing to the user because the sorted output doesn’t include their base zip code. I want to be able to include the base zip code as if there was no income range specified.
How can I include the ranged data (that uses the BETWEEN) and include the base zip code’s data so it still takes advantage of MySQL’s ORDERing of the output. Thanks!
UPDATE: Here is the working query for zip code 90210. As you can see, it won’t return 90210 as I wish because the BETWEEN because it isn’t in the income range (avg agi):
mysql> SELECT zip, city, state, avg_agi, ( 3959 * acos( cos( radians(34.088808) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-118.40612) ) + sin( radians(34.088808) ) * sin( radians( lat ) ) ) ) AS distance FROM zip_codes, avgagi where zip=zipcode and avg_agi BETWEEN 100000 and 200000 HAVING distance < 5 ORDER BY distance LIMIT 0 , 10000;
+-------+----------------+-------+---------+------------------+
| zip | city | state | avg_agi | distance |
+-------+----------------+-------+---------+------------------+
| 90069 | West Hollywood | CA | 121753 | 1.42816585190112 |
| 90211 | Beverly Hills | CA | 164538 | 2.06804933097035 |
| 90024 | Los Angeles | CA | 187134 | 2.47751318825072 |
| 90025 | Los Angeles | CA | 130983 | 3.76591348160737 |
| 91604 | Studio City | CA | 103328 | 3.8634176735557 |
| 90064 | Los Angeles | CA | 130769 | 3.95933331921038 |
| 90068 | Los Angeles | CA | 100370 | 4.52908379278674 |
+-------+----------------+-------+---------+------------------+
WHERE (data between x and y) OR (zip = z)
Should work no?