当我按计算列进行ORDER BY时,查询显着减慢 - 这可以加速吗?

时间:2012-06-19 23:41:59

标签: mysql sql-order-by query-optimization

以下查询完成时间超过25秒:

SELECT c.* , (c.age+ (UNIX_TIMESTAMP()-UNIX_TIMESTAMP(c.newdate))) AS ranking , IF(uc.id_user = 7,1,0) AS favorite
FROM c 
LEFT OUTER JOIN uc ON uc.id_cluster = c.id AND uc.id_user = '7' 
LEFT OUTER JOIN d ON d.id_cluster = c.id 
LEFT OUTER JOIN dt0 ON dt0.id_document = d.id 
LEFT OUTER JOIN t0 ON dt0.id_term = t0.id 
WHERE MATCH(t0.normalizacion) AGAINST ('term' IN NATURAL LANGUAGE MODE) 
GROUP BY c.id 
ORDER BY ranking ASC 
LIMIT 30

索引:

  • c.id PRIMARY
  • c.age INDEX
  • c.newdate INDEX
  • uc.id_user,uc.id_cluster PRIMARY
  • d.id PRIMARY
  • d.id_cluster INDEX
  • dt0.id_document,dt0.id_term PRIMARY
  • dt0.id_document INDEX
  • dt0.id_term INDEX
  • t0.id PRIMARY
  • t0.normalizacion FULLTEXT

如果删除ORDER BY子句,则只需2秒。

我一直在搜索并发现同样的索引必须用于GROUP BY和ORDER BY(尝试通过c.id排序并花费2或3秒)。如何更快地更改查询?

1 个答案:

答案 0 :(得分:1)

(巩固上述讨论)

您无法通过计算结果有效排序。要使此查询快速运行,请创建包含ranking的{​​{1}}列。然后在c.age-UNIX_TIMESTAMP(c.newdate) id上创建一个索引,即ranking,以便将GROUP BY和ORDER BY编入索引。