duancong7573 2016-04-11 21:07
浏览 110
已采纳

返回基于MYSQL中lat / lng匹配距离查询的行数?

I'm using this query to find providers within a certain distance, I know it's not an ideal way to do this and it only returns a semi-accurate distance as the crow flies, but the distance is going to have to be calculated far too many times to use any third party API's.

SELECT ( 3959 * acos( cos( radians('28.65') ) * cos( radians( lat ) ) * cos( radians( lon ) - radians('-81.21') ) + sin( radians('28.65') ) * sin( radians( lat ) ) ) ) AS distance FROM providers HAVING distance < 10

That works fine and returns all providers within 10 miles, however I want to return a count of the results, something like this:

SELECT COUNT(providers.id) AS rowcount, ( 3959 * acos( cos( radians('28.65') ) * cos( radians( lat ) ) * cos( radians( lon ) - radians('-81.21') ) + sin( radians('28.65') ) * sin( radians( lat ) ) ) ) AS distance FROM providers HAVING distance < 10

That, unfortunately, does not work.

Is there any other way to do this within the query or do I have to count the rows afterwards with PHP?

  • 写回答

1条回答 默认 最新

  • doumao8803 2016-04-11 23:23
    关注

    You can use a subquery:

    SELECT COUNT(*) FROM (
        SELECT (3959 * ACOS(COS(RADIANS('28.65')) * COS(RADIANS(`lat`)) * COS(RADIANS(`lon`) - RADIANS('-81.21')) + SIN(RADIANS('28.65')) * SIN(RADIANS(lat)))) AS distance
        FROM providers
        HAVING distance < 10
    )
    

    The inner query is your original one, and then the outer query counts the results.

    As mentioned in comments, you should alter your database to use MySQL's spatial data types, which will allow you to do this automatically and with indexes to make it faster.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题