gpt4 book ai didi

mysql - 仅获取给定列值的一行

转载 作者:太空宇宙 更新时间:2023-11-03 12:15:40 24 4
gpt4 key购买 nike

我的查询的基本结构是这样的:

  • 我有一个包含个人资料信息的个人资料
  • 我有一个包含位置坐标的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"

(选择行中的 grosstastic 将 locations 表中的 lat/lng 字段转换为距给定输入 lat/lng 的距离)

但是,我的查询使配置文件在结果中出现多次,一次是针对他分配到的每个位置。我希望每个配置文件只出现一次,其中包含距离最短的位置的信息。

我的下意识 react 是使用 group_by location_id,但我想确保我得到的位置与输入坐标的距离最短。

最佳答案

去长角牛!

让我们从在位置表中找到正确的行开始。

SELECT DISTINCT location_id
FROM locations
ORDER BY your_spherical_cosine_law_distance_formula
LIMIT 1

这将为您提供唯一的位置 ID。

现在您想将其用作子查询来获取适当的配置文件行。你这样做:

 SELECT whatever
FROM (
SELECT DISTINCT location_id
FROM locations
ORDER BY your_spherical_cosine_law_distance_formula
LIMIT 1
) AS one
JOIN location_assignment AS la ON one.location_id = la.location_id
JOIN profiles AS p on p.profile_id =la.profile_id

这应该会为您提供适当的配置文件行列表,没有重复。

你没有问这个,但我希望你没有太多的位置行。您正在使用的查询必然会扫描整个表并对每一行进行大量计算。您的 HAVING 子句确实没有帮助。为了加快速度,您需要将距离搜索与边界矩形搜索结合起来。这可能会有所帮助。 http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/

关于mysql - 仅获取给定列值的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22339229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com