我有一张城市表:
cities(..., name, x, y, ...)
用户表:
users(..., city-name, ....)
另外,我有2个变量,C和R. 第一个包含城市名称,第二个包含半径。 我需要制定有效的SQL查询,从城市C中选择半径为R的所有用户。
感谢。
答案 0 :(得分: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),那么你需要计算从英里到经度/的东西的半径/纬度计算。
使用haversine formula的效率会降低,但更准确:
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
答案 1 :(得分: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
);