zoukankan      html  css  js  c++  java
  • mysql计算距离最近的店铺

    传入参数 纬度 40.0497810000 经度 116.3424590000
    /*传入的参数为  纬度 纬度 经度 ASC升序由近至远 DESC 降序 由远到近 */
    SELECT
        *,
        ROUND(
            6378.138 * 2 * ASIN(
                SQRT(
                    POW(
                        SIN(
                            (
                                40.0497810000 * PI() / 180 - lat * PI() / 180
                            ) / 2
                        ),
                        2
                    ) + COS(40.0497810000 * PI() / 180) * COS(lat * PI() / 180) * POW(
                        SIN(
                            (
                                116.3424590000 * PI() / 180 - lon * PI() / 180
                            ) / 2
                        ),
                        2
                    )
                )
            ) * 1000
        ) AS juli
    FROM
        customer
    ORDER BY
        juli ASC

    这样会把数据库中所有店铺都计算一遍,而在实际的使用中,不太可能会发生需要计算该用户与所有其他用户的距离,然后再排序的情况,当用户数量达到一个级别时,就可以在一个较小的范围里进行搜索,而非在所有用户中进行搜索.

    所以对于这个例子,我增加了4个where条件,只对于经度和纬度大于或小于该用户1度(111公里)范围内的用户进行距离计算,同时对数据表中的经度和纬度两个列增加了索引来优化where语句执行时的速度.

    最终的sql语句如下

    $sql='select * from users_location where
                                latitude > '.$lat.'-1 and
                        
                                latitude < '.$lat.'+1 and
                        
                                longitude > '.$lon.'-1 and
                            
                                longitude < '.$lon.'+1
                            
                                order by ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) *COS(('.$lon.'* 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380 asc limit 10';
                            
  • 相关阅读:
    Train Problem(栈的应用)
    Code obfuscatio (翻译!)
    Milking Cows
    Sorting a Three-Valued Sequence(三值排序)
    Asphalting Roads(翻译!)
    FatMouse' Trade
    Fibonacci Again
    Yogurt factory
    经济节约
    Lucky Conversion(找规律)
  • 原文地址:https://www.cnblogs.com/hanshuai0921/p/6992447.html
Copyright © 2011-2022 走看看