how to get nearest value from database in mysql

后端 未结 11 1143
夕颜
夕颜 2020-12-31 16:39

I am using mySQL and CodeIgniter. I have some floating point numbers in my database such as

  • 8.3456
  • 8.5555
  • 4.5556
11条回答
  •  死守一世寂寞
    2020-12-31 17:24

    In my case, I was using the browsers geolocations and trying to find a closest city/state based on the coordinates I had in a table.

    table structure:

    id    zipcode    city_state   lat    lon
    1     12345      Example, GA  85.3   -83.2
    

    Recommend testing this vigorously before using -- probably needs some tweaks, but I came up with this as a start

    SELECT city_state, 
       zipcode, 
       ( Abs( lat - -33.867886 ) 
         + Abs( lon - -63.987) ) AS distance
    FROM   zipcodes 
    ORDER  BY distance 
    LIMIT  1;  
    

    For laravel users:

    $city = Zipcodes::selectRaw
        ('city_state, zipcode,  ( ABS( lat - ? ) + ABS( lon - ?) ) AS distance', [$lat, $lon])
            ->orderBy('distance')
            ->first();
    
    echo $city->city_state
    

    Hope this helps someone someday.

提交回复
热议问题