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

标签 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 中使用过程对这个查询有帮助吗?

非常感谢

最佳答案

试试这个:

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_idxmid 上的索引)因为它的选择性不够...

关于mysql - 此查询运行 30 秒。我该如何优化它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6928645/

相关文章:

php - 从mysql的不同列中选择值,我怎么知道哪个是哪个?

如果未找到所有值,MySQL INNER JOIN 将返回零结果

sql - 如何使用 AWS Athena 中的包含函数来查找某些文本

php - 使用 MySQL 和 PHP 检查线程中有多少帖子的最快方法

mysql - 表插入 - 多个 MySQL 数据库

mysql - Laravel 4 Eloquent + 原始查询返回 NULL

mysql - 是否可以在 bool 模式和查询扩展下执行全文索引搜索?

sql - 存储过程的表值参数可以有默认值吗

mysql - 如何用 JOIN 替换 NOT EXISTS 嵌套选择

sql - MySQL MyISAM 表性能问题重温