JPA Select - 某些特定键很慢?

时间:2014-01-21 08:22:58

标签: java sql jpa playframework

使用Play Framwork 1.x - 我已经制作了这个模型定义:

@Entity
public class ShareHistoryResult extends GenericModel {
  @Id
  @Index(name = "isinOnly")
  public String ISIN;
  @Id
  @Index(name = "calDate")
  public Date    calDate;
  public Double  opening;
  public Double  closing;
  public Double  highest;
  public Double  lowest;
  public Integer count;
  public Double  turnover;

要在特定日期之前获得最新结果,我选择:

ShareHistoryResult shareDay = ShareHistoryResult.find("calDate <= ? AND ISIN = ? AND closing > 0 ORDER BY calDate DESC", date, isin).first();

工作正常。

对于大多数isin键,请求的时间不到50毫秒。但是对于一些键(每次都相同),它需要300-400毫秒。

JPA生成的SQL:

select sharehisto0_.calDate as calDate9_, sharehisto0_.ISIN as ISIN9_, sharehisto0_.closing as closing9_, sharehisto0_.count as count9_, sharehisto0_.highest as highest9_, sharehisto0_.lowest as lowest9_, sharehisto0_.opening as opening9_, sharehisto0_.turnover as turnover9_ from ShareHistoryResult sharehisto0_ where sharehisto0_.calDate<=? and sharehisto0_.ISIN=? and sharehisto0_.closing>0 order by sharehisto0_.calDate DESC limit ?

如果我使用其中一个慢键直接在MySqlWorkbench中运行此SQL。它的闪电速度为0.02-0.2秒。

这是表的create语句(从MySqlWorkbench复制):

CREATE TABLE `ShareHistoryResult` (
  `calDate` datetime NOT NULL,
  `ISIN` varchar(255) NOT NULL,
  `closing` double DEFAULT NULL,
  `count` int(11) DEFAULT NULL,
  `highest` double DEFAULT NULL,
  `lowest` double DEFAULT NULL,
  `opening` double DEFAULT NULL,
  `turnover` double DEFAULT NULL,
  PRIMARY KEY (`calDate`,`ISIN`),
  KEY `calDate` (`calDate`),
  KEY `isinOnly` (`ISIN`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET

任何想法为什么某些键比其他键明显慢?

1 个答案:

答案 0 :(得分:0)

我意识到问题在于我选择按日期排序的所有记录。如果我改为限制日期,例如calDate&lt; =? AND calDate&gt; ? (=参数2在参数1之前的几天),然后它的评估速度非常快。

我认为.first()会消除日期范围的需要,但不会。