单独执行时快速查询,嵌套时速度慢

时间:2011-09-22 17:10:32

标签: mysql performance

我正在尝试在一堆特定日期找到最近的入场时间。我跑的时候

select max(ts) as maxts from factorprice where ts <= '2011-1-5'

它很快就会回归。

EXPLAIN提供select_type SIMPLE和“选择优化的表格”。

但是当我跑步时

select (select max(ts) from factorprice where ts <= dates.dt) as maxts, dates.dt 
   from 
   trends.dates where dates.dt in ('2011-1-6');

返回需要很长时间(~10秒)。

解释给出:

  • select_type = PRIMARY table = dates rows = 506 Extra =使用where
  • select_type = DEPENDENT SUBQUERY table = factorprice type = index possible_keys = PRIMARY key = PRIMARY keylen = 8 rows = 26599224 Extra = Using 哪里;使用索引

此查询也需要很长时间(10秒)

select dt, max(ts) as maxts from factorprice as f inner join trends.dates as d
   where ts <= dt and dt in ('2011-1-6')
   group by dt;

解释给出:

  • select_type = SIMPLE table = d type = ALL rows = 509 Extra =使用where
  • select_type = SIMPLE table = f type = range possible_keys = PRIMARY key = PRIMARY keylen = 8 rows = 26599224 Extra = Using 哪里;使用索引

我想在许多不同的日期做同样的操作。有没有办法可以有效地做到这一点?

3 个答案:

答案 0 :(得分:1)

看起来像这个错误:

http://bugs.mysql.com/bug.php?id=32665

也许如果你在dates.dt上创建一个索引,它就会消失。

答案 1 :(得分:0)

这部分SQL是依赖查询

select max(ts) from factorprice where ts <= dates.dt

对结果集中的每一行执行。因此,总时间大约是独立查询对结果集中的行进行计时的时间。

答案 2 :(得分:0)

从EXPLAIN输出判断。此查询访问日期表中的506行,然后对于每个行,在factorprice表中访问超过2600万行。 10秒做所有这一切并不算太糟糕。

我的猜测是你无意中创建了一个CROSS JOIN情况,其中一个表的每一行都与另一个表中的每一行匹配。