【发布时间】:2014-04-15 20:41:16
【问题描述】:
我的查询的基本结构是这样的:
- 我有一个包含个人资料信息的
profiles表 - 我有一个带有位置坐标的
locations表 - 我有一个
location_assignment表,其中只包含 (profile_id, location_id) 对
每个配置文件都分配到一个或多个位置,我要做的是搜索配置文件,然后按与位置坐标的距离顺序返回它们。我的查询是(仅包括相关部分)如下:
SELECT *,
(3959*acos(cos(radians(30.292424))*cos(radians(lat))*cos(radians(lng)-
radians(-97.73856))+sin(radians(30.292424))*sin(radians(lat)))) AS distance,
`profiles`.`name` as profilename,
`profiles`.`profile_id` as profile_id
FROM (`profiles`)
JOIN `location_assignment`
ON `profiles`.`profile_id` =`location_assignment`.`profile_id`
JOIN `locations`
ON `location_assignment`.`location_id` = `locations`.`location_id`
HAVING `distance` < 50
ORDER BY `distance`
LIMIT 3"
(选择行中的那个粗略的东西将locations 表中的纬度/经度字段转换为与给定输入纬度/经度的距离)
但是,我的查询使配置文件在结果中出现多次,每次分配给他的位置一次。我希望每个配置文件只出现一次,并带有最短距离的位置信息。
我的下意识反应是使用group_by location_id,但我想确保获得与输入坐标距离最小的位置。
【问题讨论】:
-
你的代码中有一个
HAVING,所以要么你缺少GROUP BY,要么你想要一个WHERE。 -
您可能希望在您的选择中指定连接类型(这些应该是 LEFT JOIN)
-
@Rafa:抱歉,我删除了一堆不相关的其他表连接(此查询跨越七个表),是的,我删除的其中一个是
WHERE。完整的子句是“WHEREprocedures.procedure_id= 18 ANDbase_price> 0 HAVINGdistancedistance”
标签: mysql sql geolocation proximity