dongyou5271 2015-06-16 11:42
浏览 34

查找附近的邮政编码myquery优化

I have need find nearby postcode of point in google map , I am using SQL – Haversine formula. below is my query

 $query = $this->db->query("SELECT Postcode,latitude,longtitude, ACOS(COS(RADIANS(latitude)) *
    COS(RADIANS(longtitude)) * COS(RADIANS($latitude)) * COS(RADIANS($longtitude)) +
    COS(RADIANS(latitude)) * SIN(RADIANS(longtitude)) * COS(RADIANS($latitude)) * 
    SIN(RADIANS($longtitude)) + SIN(RADIANS(latitude)) * SIN(RADIANS($latitude))) * 
    3963.1 AS Distance
    FROM postalscheme   
    HAVING Distance <= 4  "); 

Data is fetched correctly using this query, but my problem is its taking long time to fetch data [3 or 5 min for fetch 20 thousand to 60 thousand data ] .

please help me to optimize this query and work fast .

  • 写回答

1条回答 默认 最新

  • dtcuv8044 2015-06-16 14:40
    关注

    you can limit the range of data you have to calculate distances for when you limit the latitude/longitude values to the ones nearby. (formulas coming from these slides (page 12ff) This works when you calculate by miles... otherwise you have to adjust the "69" with the right value for kilometers.

    1° of latitude ~= 69 miles 
    1° of longitude ~= cos(latitude)*69
    

    When you want to calculate the longitude and latitude for the smaller rectangle, you can use (with your variables above):

    $dist = 4; // the distance from your query above
    $lon1 = $longtitude - $dist / abs(cos(deg2rad($latitude))*69);
    $lon2 = $longtitude + $dist / abs(cos(deg2rad($latitude))*69);
    $lat1 = $latitude - ($dist / 69);
    $lat2 = $latitude + ($dist / 69);
    

    and then you modify your query like so:

    $query = $this->db->query("SELECT Postcode,latitude,longtitude, ACOS(COS(RADIANS(latitude)) *
        COS(RADIANS(longtitude)) * COS(RADIANS($latitude)) * COS(RADIANS($longtitude)) +
        COS(RADIANS(latitude)) * SIN(RADIANS(longtitude)) * COS(RADIANS($latitude)) * 
        SIN(RADIANS($longtitude)) + SIN(RADIANS(latitude)) * SIN(RADIANS($latitude))) * 
        3963.1 AS Distance
        FROM postalscheme   
        WHERE longitude BETWEEN $lon1 AND $lon2 
        AND latitude BETWEEN $lat1 AND $lat2
        HAVING Distance <= $dist  ");
    

    This should improve the overall speed drastically.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题