此查询在30秒内运行。我该如何优化它?

时间:2011-08-03 15:04:06

标签: mysql sql query-optimization

在此处跟进我之前的问题: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中的过程会对这个查询有帮助吗?

非常感谢

5 个答案:

答案 0 :(得分:3)

试试这个:

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

此查询将受益于(chapterno,hitcount)上的索引。此外,根据您的数据(具有相同值MID)和EXPLAIN输出的许多记录,您似乎不需要mid上的索引(我相信mid_idxmid)的索引,因为它没有足够的选择性......

答案 1 :(得分:1)

所有这三个字段

CREATE INDEXt1.id, t1.hitcount, t1.chapterno

答案 2 :(得分:1)

尝试在Mid和ChapterNo上创建索引。可能甚至在HitCount上,但请记住,索引会影响插入/更新的性能,所以不要到处创建索引。我会说,从Mid开始,测试,然后在Chapter。

上创建索引

答案 3 :(得分:1)

ALTER TABLE `chapter` ADD INDEX `cindex_1` (`mid` ASC, `hitcount` ASC, `chapterno` DESC);
ALTER TABLE `chapter` ADD INDEX `cindex_2` (`mid` ASC, `chapterno` ASC, `hitcount` DESC);

第一个索引优化主查询,第二个索引优化子查询。

答案 4 :(得分:0)

这就是我的所作所为:

SELECT c1.ID, c1.ChapterNo, c1.HitCount 
FROM chapter c1 JOIN (
SELECT ChapterNo, max(HitCount) max 
FROM chapter c2 
WHERE MID=2524 
GROUP BY ChapterNo) c3 
ON c1.ChapterNo=c3.ChapterNo AND c1.HitCount=c3.max;

有2个索引:一个在ChapterNo上,一个在HitCount上,另一个在MID上

立即返回100k行。