Date = max(Date)运行缓慢

时间:2016-02-08 01:05:21

标签: mysql sql

我在historical_data表中有大约600万条记录。我试图找到所有符号,其中最后记录的行不等于表上的最高日期。我相信这个查询会起作用,但它需要永远运行。事实上,它每次都会超时。有没有办法让这个查询运行得更快?

select symbol, histDate
from historical_data as a
where histDate =
    (select max(histDate)
     from historical_data as b
     where a.symbol = b.symbol);

1 个答案:

答案 0 :(得分:1)

您需要此查询的索引。最佳索引是historical_data(symbol, histdate)

您可能会发现将查询短语更快:

select hd.*
from historical_data hd join
     (select symbol, max(histDate) as maxhd
      from historical_data
      group by symbol
     ) s
     on hd.histDate = s.histDate;

编辑:

糟糕。您的示例查询不会执行文本所需的内容。为此:

select symbol
from historical_data hd cross join
     (select max(histDate) as maxhd from historical_data) m
group by symbol, maxhd
having max(hd.histDate) <> maxhd;