MySQL此查询的精确语法:查找附近的位置

时间:2015-11-30 11:01:15

标签: php mysql google-maps geo

下面是一个查询,用于在用户的lat,lon和Radius附近找到产品

我希望此功能只是返回商店的ID ...查询似乎无法正常工作

SELECT
                   product_id

                FROM
                    sm_products
                WHERE
                    ROUND(
                        $earthRadius * ACOS(  
                            SIN( $userlat*PI()/180 ) * SIN( geo_lat*PI()/180 )
                            + COS( $userlat*PI()/180 ) * COS( geo_lat*PI()/180 )  *  COS( (geo_lon*PI()/180) - ($userlon*PI()/180) )   ) 
                    , 1) AS distance <= $userRadius
                ORDER BY
                    distance ASC

以下查询正在工作..但是ID确实返回我不需要的ID和距离...我只需要在半径范围内返回product_id

SELECT
                ROUND(
                    $earthRadius * ACOS(  
                        SIN( $userlat*PI()/180 ) * SIN( geo_lat*PI()/180 )
                        + COS( $userlat*PI()/180 ) * COS( geo_lat*PI()/180 )  *  COS( (geo_lon*PI()/180) - ($userlon*PI()/180) )   ) 
                , 1)
                AS distance,
                product_id

            FROM
                sm_products
            HAVING
                distance <= $userRadius    
            ORDER BY
                distance ASC

任何帮助?

编辑(函数调用)

$params['product_id'] = $this->productsInRadius($userlat, $userlon, $radius);

2 个答案:

答案 0 :(得分:0)

@JonStirling此查询有效...但我不确定它是否是一个好的练习

SELECT
                    product_id
                FROM
                    sm_products
                WHERE
                    ROUND(
                        $earthRadius * ACOS(  
                            SIN( $userlat*PI()/180 ) * SIN( geo_lat*PI()/180 )
                            + COS( $userlat*PI()/180 ) * COS( geo_lat*PI()/180 )  *  COS( (geo_lon*PI()/180) - ($userlon*PI()/180) )   ) 
                    , 1) <= $userRadius    
                ORDER BY 
                ROUND(
                        $earthRadius * ACOS(  
                            SIN( $userlat*PI()/180 ) * SIN( geo_lat*PI()/180 )
                            + COS( $userlat*PI()/180 ) * COS( geo_lat*PI()/180 )  *  COS( (geo_lon*PI()/180) - ($userlon*PI()/180) )   ) 
                    , 1) ASC

答案 1 :(得分:0)

所以我认为以下应该可行,但我目前无法测试它。如果它错了,请指出它,我会放弃答案。

SELECT product_id
FROM (
    SELECT
        product_id,
        ROUND(
            $earthRadius * ACOS(SIN( $userlat*PI()/180 ) * SIN(geo_lat*PI()/180 ) + COS( $userlat*PI()/180 ) * COS( geo_lat*PI()/180     ) * COS( (geo_lon*PI()/180) - ($userlon*PI()/180))   
        , 1) AS distance
    FROM
        sm_products
    WHERE
        distance <= $userRadius
)
ORDER BY
   distance ASC;