MySQL计算距离SQL语句代码示例
/**
*
* @param $lng string 外部经度
* @param $lat string 外部纬度
* @param $lngField string 数据表的纬度字段
* @param $latField string 数据表的经度字段
* @param $alias string 排序字段
* @return string
*/
function get_distance_sql($lng, $lat, $lngField = '`long`', $latField = '`lat`', $alias = 'distance')
{
return "6371.01 * ACOS(COS(RADIANS($latField)) * COS(RADIANS($lat)) * COS(RADIANS($lng) - RADIANS($lngField)) + SIN(RADIANS($latField)) * SIN(RADIANS($lat))) as $alias";
}
使用示例:
$field = '*';
if ($long && $lat) {
$field .= "," . get_distance_sql($long, $lat);
}
$list = Model::Dynamic()
->with(['worker', 'worker_user'])
->field($field)
->order('distance','asc')
->select();