【发布时间】:2009-11-17 20:54:44
【问题描述】:
我有一个包含美国所有邮政编码的数据库表,其中包括每个邮政编码的城市、州、纬度和经度。我还有一个点的数据库表,每个点都有一个与之相关的纬度和经度。我希望能够使用 1 个 MySQL 查询为我提供 zipcodes 表中所有唯一城市/州组合的列表,以及该城市/州给定半径内的点总数。我可以使用以下查询获取唯一的城市/州列表:
select city,state,latitude,longitude
from zipcodes
group by city,state order by state,city;
我可以使用以下查询获取纬度为“$lat”和经度为“$lon”的特定城市 100 英里半径内的点数:
select count(*)
from points
where (3959 * acos(cos(radians($lat)) * cos(radians(latitude)) * cos(radians(longitude) - radians($lon)) + sin(radians($lat)) * sin(radians(latitude)))) < 100;
我无法做的是弄清楚如何以一种不会杀死我的数据库的方式组合这些查询。这是我悲伤的尝试之一:
select city,state,latitude,longitude,
(select count(*) from points
where status="A" AND
(3959 * acos(cos(radians(zipcodes.latitude)) * cos(radians(latitude)) * cos(radians(longitude) - radians(zipcodes.longitude)) + sin(radians(zipcodes.latitude)) * sin(radians(latitude)))) < 100) as 'points'
from zipcodes
group by city,state order by state,city;
这些表目前有以下索引:
Zipcodes - `zip` (zip)
Zipcodes - `location` (state,city)
Points - `status_length_location` (status,length,longitude,latitude)
当我在之前的 MySQL 查询之前运行解释时,输出如下:
+----+--------------------+----------+------+------------------------+------------------------+---------+-------+-------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+----------+------+------------------------+------------------------+---------+-------+-------+---------------------------------+
| 1 | PRIMARY | zipcodes | ALL | NULL | NULL | NULL | NULL | 43187 | Using temporary; Using filesort |
| 2 | DEPENDENT SUBQUERY | points | ref | status_length_location | status_length_location | 2 | const | 16473 | Using where; Using index |
+----+--------------------+----------+------+------------------------+------------------------+---------+-------+-------+---------------------------------+
我知道我可以遍历所有邮政编码并计算给定半径内的匹配点数,但点表将一直在增长,我宁愿在邮政编码数据库中没有过时的点总数。我希望那里的 MySQL 大师可以告诉我我的方式的错误。提前感谢您的帮助!
【问题讨论】:
标签: mysql geolocation query-optimization