I would like to know how to optimize the following SQL to let my server load faster and take low usage?
I need to calculate the radius distance for a US ZIP Code to get the result, such as 50 miles from a particular ZIP Code ( using latitude and longitude to calculate ) and to getting how many other data ( e.g. others ZIP Code ) from my database.
Once I get the result ( for example got 350 rows of different ZIP Codes within 50 miles from particular ZIP Code ), I need to passing them into another query to count the total rows and display it in simple and one result for me to read. Here is an example of my query:
SELECT count(*)
FROM
( SELECT b.ID, ROUND((acos(sin(3.142/180*32.91336) * sin(3.142/180*z.latitude) + cos(3.142/180*32.91336) * cos(3.142/180*z.latitude) * cos((3.142/180*z.longitude) - (3.142/180*-85.93836))) * 3959),2) AS distance
FROM zipcode2business.accountants b LEFT JOIN zipcodeworld.storelocator_us z ON b.ZIPCODE = z.ZIP_CODE
WHERE z.latitude != 32.91336 AND z.longitude != -85.93836
AND b.STATE='AL'
HAVING distance between 0 AND 50)
as total;
Hopefully I didn't done wrongly, it displays correct result ( 350 rows ), but I need an optimized way to runs it because this SQL gave me a high CPU usage to load. When I do EXPLAIN for this query, it display following:
+----+-------------+-------+--------+------------------+---------+---------+----------------------------+------+------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+------------------+---------+---------+----------------------------+------+------------------------------+
| 1 | PRIMARY | NULL | NULL | NULL | NULL | NULL | NULL | NULL | Select tables optimized away |
| 2 | DERIVED | b | ref | ZIPCODE,STATE | STATE | 4 | | 3900 | Using where |
| 2 | DERIVED | z | eq_ref | PRIMARY,LAT_LONG | PRIMARY | 9 | zipcode2business.b.ZIPCODE | 1 | Using where |
+----+-------------+-------+--------+------------------+---------+---------+----------------------------+------+------------------------------+
3 rows in set (0.20 sec)
Now, from above explanation, the "Select tables optimized away" in EXTRA is a good thing? Please kindly show me one most perfect optimization SQL to do this query.