I am very new to MySQL and databases in general but I have a query that seems to be taking a long time. I am finding locations from a location database of about 700,000 that are within 5 miles of another location using lat and lon coordinates. The problem is, it’s taking 2.12 seconds for the query and I’m worried once I start getting traffic, MySQL will jam. Here is my code:
SELECT *,((ACOS(SIN(44.4726 * PI() / 180) * SIN(lat * PI() / 180) + COS(44.4726 * PI() / 180) * COS(lat * PI() / 180) * COS((-93.1785 - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM locations HAVING distance<=5 ORDER BY distance ASC LIMIT 30;
I have the lat and lon fields indexed but it still takes a long time. Is this to be expected with what I’m asking the server to do? Could I speed it up by adding
WHERE state = "$state"
And if so where would I add that in the Select?
That query is going to seq scan the entire table because there’s really not a filter on it that doesn’t derive from a calculated value (distance). Adding a where clause that filters by an indexed column will definitely help eliminate some overhead, but only if the DB believes that there’s enough data in the table to warrant using the index instead of the table. Thus, make sure you analyze it as well.
The logic with the distance being in the query is incredibly ugly, but I can see why you wouldn’t want to transmit 700k+ rows over the wire every time you select from the table. It looks like you may be doing spatial calculations and might be wise to investigate spatial data types and indexes.
Ed: Also, your question about a where clause…