此查询中使用的基本邮政编码是90210的lat / lng,其平均agi(2008年)超过$ 400k。由于BETWEEN范围为100000和200000,我不希望它出现在此输出中。
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 |
+-------+----------------+-------+---------+------------------+
但是,对于我的应用程序,我需要它在输出中包含基本邮政编码。有人建议我使用带有OR的WHERE来表示zip =“90210”,但是我很难搞清楚如何完成这项工作。当我试图加入这个建议时,它旋转的时间最长,永远不会回来。
如何修改上述MySQL查询,使其包含邮政编码90210,无论BETWEEN范围如何。谢谢!
答案 0 :(得分:2)
使用UNION语句可能更容易:
SELECT
zip, city, state, avg_agi, 0 AS distance
FROM
zip_codes, avgagi
where
zip=zipcode
UNION
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;
否则试试这个:
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(zip = 90210
OR avg_agi BETWEEN 100000 and 200000 )
HAVING
distance < 5 ORDER BY distance LIMIT 0 , 10000;