MYSQL计数大大减慢了查询

时间:2016-11-15 12:06:02

标签: mysql count

我有一个mysql查询,它返回给定距离内的行,如下所示。查询运行大约0.002秒,这很好:

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)

当我尝试使用下面的查询返回行数时,执行时间会急剧增加到0.024秒。是否有更快的方法来计算结果数量。

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;

这是关于secondquery的解释,其中包括计数

1  PRIMARY  <derived2>  ALL   NULL  NULL  NULL  NULL  10352  
2  DERIVED  adverts     range r...  b..   11    NULL  10352  Using where; Using index

1 个答案:

答案 0 :(得分:-1)

假设问题来自存储第一个查询结果的临时表,我建议更改查询以避免嵌套选择:

SELECT count(*)
  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) 
  AND (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 ) <= 49);