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

时间:2018-06-08 13:05:34

标签: mysql group-by geospatial greatest-n-per-group

我有3个表格,其中包含以下字段:

  1. 组织(org_id,org_name,location)
  2. 办公室(office_id,office_name,location, org_id
  3. 项目(project_id,project_name,location)
  4. 我想找到离特定项目最近的办事处

    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)函数。删除它会删除错误,但我没有得到所需的结果。

      

    ERROR 1111(HY000):无效使用群组功能

    我做错了什么?任何想法高度赞赏。感谢

1 个答案:

答案 0 :(得分:1)

  

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

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;