【发布时间】:2014-01-09 03:26:08
【问题描述】:
我在 Mysql 中运行了如下查询:
EXPLAIN
SELECT *
FROM(
SELECT * # Select Number 2
FROM post
WHERE parentid = 13
ORDER BY time, id
LIMIT 1, 10
) post13_childs
JOIN post post13_childs_childs
ON post13_childs_childs.parentid = post13_childs.id
结果是:
id |select_type |table |type |possible_keys |key |key_len |ref |rows |Extra
1 |PRIMARY |<derived2> |ALL | NULL | NULL |NULL |NULL |10 |
1 |PRIMARY |post13_childs_childs|ref |parentid |parentid |9 |post13_childs.id |10 |Using where
2 |DERIVED |post |ALL |parentid |parentid |9 | |153153 |Using where; Using filesort
这意味着它使用了索引parentid,但由于ALL 和153153 而扫描了所有行。
为什么索引不能帮助Full Scannig?
虽然如果我运行派生查询(选择 #2)单独,如下所示:
Explain
SELECT * FROM post
WHERE parentid=13
ORDER BY time , id
LIMIT 1,10
结果会很理想:
id |select_type |table |type |possible_keys |key |key_len |ref |rows |Extra
1 |SIMPLE |post |ref |parentid |parentid |9 |const|41 |Using where; Using filesort
编辑:
表post 有这些索引:
- id(主要)
- 父代
- 时间,id (timeid)
总行数 --> 141280.13 (parentid=13) 的孩子数量 --> 4111523 的孩子数 --> 10119
当我添加 (parent,time,id) 的索引时,第一次查询的问题将通过 13 的 explin 输出解决 --> 40 行,输入:ref
对于11523 --> 19538 行,输入:ref!!!这意味着检查11423 的所有子行,而我限制了前 10 行。
【问题讨论】:
-
您需要帮助改进和优化此查询吗?如果是这样,我们需要查看整个查询(及其解释)
-
@Strawberry,对不起。我现在编辑并写了细节。
-
尝试为
(parentid, time, id)创建索引。进一步参考mysqlperformanceblog.com/2006/09/01/… -
你不能利用派生表中的索引......
-
@Meherzad,为什么?真的吗?是一个可用的参考。
标签: mysql sql indexing query-optimization explain