0

我有一个城市表:

cities(..., name, x, y, ...)

和用户表:

users(..., city-name, ....)

另外,我有 2 个变量,C 和 R。第一个包含城市名称,第二个包含半径。我需要制定有效的 SQL 查询,从城市 C 中选择半径 R 中的所有用户。

谢谢。

4

2 回答 2

3

使用粗略的距离计算:-

SELECT
FROM Users
INNER JOIN Cities UsersCities
ON Users.CityName = UsersCities.CityName
INNER JOIN Cities
ON SQRT(POW((Cities.x-UsersCities.X), 2) + POW((Cities.y-UsersCities.Y), 2)) < someradiusconverted
WHERE Cities.CityName = somecityname

不会在经度的最末端工作(例如,如果用户的x坐标是 179 而城市的坐标是 -179),而且您需要计算从英里到可用于经度/纬度计算的东西的半径。

使用hasrsine 公式效率会降低,但会更准确:

SELECT Users.*
FROM Users
INNER JOIN Cities UsersCities
ON Users.CityName = UsersCities.CityName
INNER JOIN Cities
ON ( 3959 * acos( cos( radians( Cities.y ) ) * cos( radians( UsersCities.Y ) ) * cos( radians( UsersCities.X ) - radians( Cities.x ) ) + sin( radians( Cities.y ) ) * sin( radians( UsersCities.Y ) ) ) ) < someradius
WHERE Cities.CityName = somecityname
于 2013-07-09T08:37:53.443 回答
0

我会想到以下几点:

select
    user_id
from
    Users
where
    city_id in (
        select
            city_id
        from
            Cities
        where
            sqrt(((select x from Cities where name = "London") - x)^2 + ((select y from Cities where name = "London")-y)^2) < 50
);
于 2013-07-09T07:21:34.463 回答