title: Geolocation MySQL Query
body: <p>I run a geolocation-based social network.  Members can see other members based on how close they are.</p>
  
  <p>Right now my MySQL query looks like:</p>
  
  <pre><code>$lat_min = $geo['user_lat'] - 5;
  $lat_max = $geo['user_lat'] + 5;
  $long_min = $geo['user_long'] - 5;
  $long_max = $geo['user_long'] + 5;    
  
  $members_query = "SELECT " . $fields . " FROM members WHERE (user_lat BETWEEN " . $lat_min . " AND " . $lat_max . " AND user_long BETWEEN " . $long_min . " AND " . $long_max . ") OR (gc_lat BETWEEN " . $lat_min . " AND " . $lat_max . " AND gc_long BETWEEN " . $long_min . " AND " . $long_max . ")";
  </code></pre>
  
  <p><code>user_lat</code> and <code>user_long</code> are coordinates based on geolocation if they have it turned on in their browser.  <code>gc_lat</code> and <code>gc_long</code> and coordinates based on their IP address.  These rows are all indexed in the database. I am pulling all members within 10 degrees.</p>
  
  <p>The problem is this query takes about 2 seconds to perform for our 250,000+ members, and we want the site to scale.</p>
  
  <p><strong>ATTEMPT 2:</strong> I have tried assigning quadrants to each member e.g. "36x-99" ... I am rounding off the latitude and longitude to the nearest multiple of 3 to label the quadrant, and then I only pull quadrants within 12 degrees of the quadrant the member is in.</p>
  
  <pre><code>$members_query = "SELECT " . $fields . " FROM members WHERE quadrant IN ('36x-99', '33x-99', '30x-99', ...);
  </code></pre>
  
  <p>This gave me no noticeable difference in query speed.</p>
  
  <p>Anyone have any ideas of what I should do?  I need to find a solution that will allow the site to scale better.</p>