1

以下查询需要 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 初级
  • 年龄指数
  • c.newdate 索引
  • uc.id_user, uc.id_cluster PRIMARY
  • d.id 初级
  • d.id_cluster 索引
  • dt0.id_document, dt0.id_term PRIMARY
  • dt0.id_document 索引
  • dt0.id_term 索引
  • t0.id 主要
  • t0.normalizacion FULLTEXT

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

我一直在搜索,发现 GROUP BY 和 ORDER BY 必须使用相同的索引(尝试按 c.id 排序并花费 2 或 3 秒)。如何将查询更改为更快?

4

1 回答 1

1

(巩固上面的讨论)

您无法通过计算结果有效地排序。要使此查询快速运行,请创建一个ranking包含c.age-UNIX_TIMESTAMP(c.newdate). id 然后在and 上创建一个索引ranking,即使CREATE INDEX id_ranking ON c (id, ranking)GROUP BY 和 ORDER BY 都被索引。

于 2012-06-21T12:08:44.030 回答