我有以下MySQL查询:
SELECT t1.id, t1.releaseid, t1.site, t1.date, t2.pos FROM `tracers` as t1
LEFT JOIN (
SELECT `releaseid`, `date`, COUNT(*) AS `pos`
FROM `tracers` GROUP BY `releaseid`
) AS t2 ON t1.releaseid = t2.releaseid AND t2.date <= t1.date
ORDER BY `date` DESC , `pos` DESC LIMIT 0 , 100
想法是选择一个版本并计算在记录日期之前还有多少其他网站已经发布它,以获得该位置。
解释说:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY t1 ALL NULL NULL NULL NULL 498422 Using temporary; Using filesort
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 91661
2 DERIVED tracers index NULL releaseid 4 NULL 498422
有关如何消除使用临时的任何建议;使用filesort?这需要一个漫长的时间。我曾经想过并尝试过的索引没有任何帮助。
答案 0 :(得分:0)
尝试在tracers.releaseid
上添加一个索引,在tracers.date
答案 1 :(得分:0)
答案 2 :(得分:0)
尝试使用两个索引,一个在(date)
上,一个在(releaseid, date)
上。
另一件事是你的查询似乎没有做你所描述的。它真的算得上了吗?
尝试将其重写为:
SELECT t1.id, t1.releaseid, t1.site, t1.`date`
, COUNT(*) AS pos
FROM tracers AS t1
JOIN tracers AS t2
ON t2.releaseid = t1.releaseid
AND t2.`date` <= t1.`date`
GROUP BY t1.releaseid
ORDER BY t1.`date` DESC
, pos DESC
LIMIT 0 , 100
或作为:
SELECT t1.id, t1.releaseid, t1.site, t1.`date`
, ( SELECT COUNT(*)
FROM tracers AS t2
WHERE t2.releaseid = t1.releaseid
AND t2.`date` <= t1.`date`
) AS pos
FROM tracers AS t1
ORDER BY t1.`date` DESC
, pos DESC
LIMIT 0 , 100
答案 3 :(得分:0)
下面的答案可能不会更改解释输出,但是如果您的主要问题是排序数据,它通过删除订单子句识别将使您的查询运行更快,请尝试首先对子查询连接表进行排序您的查询将是:
SELECT t1.id, t1.releaseid, t1.site, t1.date, t2.pos FROM `tracers` as t1
LEFT JOIN (
SELECT `releaseid`, `date`, COUNT(*) AS `pos`
FROM `tracers` GROUP BY `releaseid`
ORDER BY `pos` DESC -- additional order
) AS t2 ON t1.releaseid = t2.releaseid AND t2.date <= t1.date
ORDER BY `date` DESC , `pos` DESC LIMIT 0 , 100
注意:我的db版本是mysql-5.0.96-x64,也许在另一个版本中你会得到不同的结果。