作为我之前在这里提出的问题的后续:Link
这些是我的表格:
-----------------------------------
ID | ChapterNo | HitCount | MID
-----------------------------------
1 | 2 | 1000 | 1
2 | 2 | 2000 | 1
3 | 1 | 3000 | 1
4 | 3 | 1000 | 1
5 | 1 | 3500 | 1
-----------------------------------
为了存档结果,我尝试使用 ff 查询:
SELECT t1.id, t1.hitcount, t1.chapterno
FROM chapter as t1
WHERE t1.hitcount = (select max(hitcount) from chapter where chapterno = t1.chapterno and `mid` = t1.`mid`)
AND t1.`mid` = '2524'
ORDER BY t1.chapterno DESC
ID | ChapterNo | HitCount |
---------------------------
4 | 3 | 1000 |
2 | 2 | 2000 |
5 | 1 | 3500 |
---------------------------
这个查询一开始似乎工作得很好,但在我导入 80,000 条记录进行测试和实现之后,规模变大了。我发现这运行了 30 秒。解释显示:
sel_type table type posible_key key keyLen ref rows Extra
PRIMARY t1 ref mid_idx mid_idx 8 const *3289* Using where; Using filesort
PRIMARY chapter ref mid_idx mid_idx 8 m.t1.mid *17* Using where; Using temporary; Using filesort
结果集是 640 行。有什么真正的好方法可以针对更大的表进行优化吗?由于此表,尤其是此查询将来会增长更多。
在 mysql 中使用过程对这个查询有帮助吗?
非常感谢
最佳答案
试试这个:
SELECT a.id, X.chapterno, X.mid, X.hitcount
FROM
(select chapterno, max(hitcount) as hitcount
from chapter
WHERE mid = 2524
group by chapterno)X
INNER JOIN chapter a ON (a.chapterno = X.chapterno AND a.mid=X.mid)
ORDER BY X.chapterno DESC
此查询将受益于索引 on(chapterno,hitcount
)。此外,从您的数据(许多具有相同 MID
值的记录)和 EXPLAIN
输出来看,您似乎不需要 mid
上的索引> (我相信 mid_idx
是 mid
上的索引)因为它的选择性不够...
关于mysql - 此查询运行 30 秒。我该如何优化它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6928645/