我有一个表foo
与(其他20个)列bar
,baz
和quux
与索引baz
和quux
。该表有500k行。为什么MAX()比ORDER BY ... LIMIT 1慢100倍?
为什么以下查询在速度上差异如此之大?查询A需要0.3s,而查询B需要28s。
查询
select baz from foo
where bar = :bar
and quux = (select quux from foo where bar = :bar order by quux desc limit 1)
解释
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY foo ref quuxIdx quuxIdx 9 const 2 "Using where"
2 SUBQUERY foo index NULL quuxIdx 9 NULL 1 "Using where"
查询乙
select baz from foo
where bar = :bar
and quux = (select MAX(quux) from foo where bar = :bar)
说明
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY foo ref quuxIdx quuxIdx 9 const 2 "Using where"
2 SUBQUERY foo ALL NULL NULL NULL NULL 448060 "Using where"
我使用MySQL 5.1.34。
'LiMIT 1'意味着采取1行并停止,不是吗?查询B是O(n * m) – jondinham
@PaulDinh似乎两个查询的结果都是相同的,最有可能与操作顺序有关,第一种情况下它通过quux和搜索栏从结果中快速排序(快速)搜索栏(需要检查整个表)从未分类,然后排序,以找到最大 –
@Viktor,你可以请显示 '解释选择baz从foo 其中bar =:bar 和quux =(选择quux从foo其中quux = MAX(quux)and bar =:bar)' '说明从foo中选择baz 其中bar =:bar 和quux =(从foo选择quux,其中quux = MAX(quux)和bar =:bar limit 1)' –