0

此查询中使用的基本邮政编码是 90210 的 lat/lng,其平均 agi(2008 年)超过 40 万美元。由于介于 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 |
+-------+----------------+-------+---------+------------------+

但是,对于我的应用程序,我需要它在输出中包含基本邮政编码。有人建议我对 zip="90210" 使用带有 OR 的 WHERE,但是我很难弄清楚如何使它工作。当我尝试采纳这个建议时,它会旋转最长时间并且永远不会回来。

无论 BETWEEN 范围如何,如何修改上述 MySQL 查询以使其包含 90210 的邮政编码。谢谢!

4

1 回答 1

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;
于 2012-10-08T07:35:43.063 回答