I have a mysql query which returns rows within a given distance as below. The query runs in around 0.002 seconds which is fine :
SELECT round( sqrt( ( ( (adverts.latitude - '53.757729') * (adverts.latitude - '53.757729') ) * 69.1 * 69.1 ) + ( (adverts.longitude - '-2.70344') * (adverts.longitude - '-2.70344') * 53 * 53 ) ), 1 ) as distance
FROM adverts
WHERE (adverts.status = 1)
AND (adverts.approved = 1)
AND (adverts.type_id = 3)
AND (adverts.latitude BETWEEN 53.049320633786 AND 54.466137366214)
AND (adverts.longitude BETWEEN -3.9017500913496 AND -1.5051299086504)
having (distance <= 49)
When I try to return the count of the rows using the query below, the execution time increases dramatically to 0.024 seconds. Is there a faster way to get a count of the number of results.
SELECT count(*) from (SELECT round( sqrt( ( ( (adverts.latitude - '53.757729') * (adverts.latitude - '53.757729') ) * 69.1 * 69.1 ) + ( (adverts.longitude - '-2.70344') * (adverts.longitude - '-2.70344') * 53 * 53 ) ), 1 ) as distance
FROM adverts
WHERE (adverts.status = 1)
AND (adverts.approved = 1)
AND (adverts.type_id = 3)
AND (adverts.latitude BETWEEN 53.049320633786 AND 54.466137366214)
AND (adverts.longitude BETWEEN -3.9017500913496 AND -1.5051299086504)
having (distance <= 49)) as x;
Here is the explain on the secondquery which includes the count
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 10352
2 DERIVED adverts range r... b.. 11 NULL 10352 Using where; Using index