在mysql中计算空间距离并按距离排序

vfh0ocws  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(507)

我有3个带有以下字段的表:
组织(组织id、组织名称、位置)
办公室(办公室id、办公室名称、位置、组织id)
项目(项目id、项目名称、位置)
我想找到离某个项目最近的办公室

SELECT office.office_name, org.org_name, 
       st_distance_sphere(office.location, project.location)*0.001 as 
       distance 
FROM   office JOIN org JOIN project
WHERE  office.org_id=org.org_id AND 
       project.project_id=7 
ORDER BY distance asc;

上面的查询工作,并给我最接近的办公室到一个项目,但我需要得到每个组织只有一个最近的办公室
因此,我尝试使用以下半连接

SELECT office.office_name, org.org_name, 
       st_distance_sphere(office.location, project.location)*0.001 as  
       distance 
FROM  office JOIN org JOIN project  
INNER JOIN 
  ( SELECT org.org_id as orgid1, 
       min(st_distance_sphere(office.location, project.location)*0.0001) as 
       distance1 
   FROM office JOIN org JOIN project 
   WHERE 
      office.org_id=org.org_id and project.project_id=7
   GROUP BY org.org_id
   ) AS t 
     ON t.orgid1=org.org_id and t.distance1=min(st_distance_sphere(office.location,project.location)*0.001) 
 WHERE  office.org_id=org.org_id AND project.project_id=7 ;

使用这个,我得到以下错误,原因似乎是min(st_distance_sphere)函数。删除它会删除错误,但是我没有得到想要的结果。
错误1111(hy000):组函数的使用无效
我做错什么了?任何想法都非常感谢。谢谢

qcuzuvrc

qcuzuvrc1#

我只需要得到一个最近的办公室每个组织

SELECT 
  A.office_name, A.org_name, A.distance
FROM
  (SELECT 
    office.office_name,
    org.org_name, 
    st_distance_sphere(office.location, project.location)*0.001 as distance 
  FROM  office JOIN org JOIN project
  WHERE  office.org_id=org.org_id AND 
       project.project_id=7) A 
  JOIN 
  (SELECT 
     org.org_name, 
     MIN(st_distance_sphere(office.location, project.location)*0.001) as distance 
  FROM   office JOIN org JOIN project
  WHERE  office.org_id=org.org_id AND 
       project.project_id=7
  GROUP BY org.org_name) B
  ON A.org_name=B.org_name AND A.distance=B.distance
ORDER BY A.distance ASC;

相关问题