MySQL Closest location lat/long

Discussion in 'Databases' started by HorrorMovies, Apr 22, 2013.

  1. #1
    In Short:
    I have a table called locations which stores a user_id, a route_id, created_at, lat and long. The table has around 400K rows and when I query the DB it takes about 10 minutes for it to return.

    The Long:
    I am trying to get routes which are closest to a user, for this I have the users current lat and long. I am wanting to get routes that have the first location (so the start of the route) within 50 miles of the users current lat/long.

    I think the problem is its picking up every location and not just the single location for the start of the route, how would I target the first location? Also, when I look at what the query is doing it gets stuck in the status of moving to a temp table.

    SQL
    $latitude = current lat
    $longitude = current long
    $max_distance = 50 miles
    SELECT *,  SQRT(
                POW(69.1 * (lat - $latitude), 2) +
                POW(69.1 * ($longitude - `long`) * COS(lat / 57.3), 2)) AS distance
                FROM `routes` JOIN `locations` ON `routes`.`id` = `locations`.`route_id`
                GROUP BY route_id
                HAVING distance < $max_distance
                ORDER BY rating DESC LIMIT
    Code (markup):
     
    HorrorMovies, Apr 22, 2013 IP
  2. HorrorMovies

    HorrorMovies Notable Member

    Messages:
    1,466
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    250
    #2
    Never Mind I have found the solution I needed. using the MIN mysql operator on the created_at field.
     
    HorrorMovies, Apr 22, 2013 IP