我有一个名为
以下两个查询为什么速度相差如此之大?查询A只需要0.3秒,而查询B需要28秒。 查询A:
解释,说明
查询 B
解释,说明
我使用的是MySQL 5.1.34版本。
foo
的表格,其中包含20个其他列,包括bar
、baz
和quux
。在baz
和quux
上都建有索引。该表格共有约50万行。以下两个查询为什么速度相差如此之大?查询A只需要0.3秒,而查询B需要28秒。 查询A:
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"
查询 B
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版本。