数据库
首页 > 数据库> > MYSQL简单移动平均值计算

MYSQL简单移动平均值计算

作者:互联网

以下MySql更新状态似乎需要花费过多的时间来执行所提供的记录集(~5000条记录).下面的更新语句平均需要12秒才能执行.我目前计划对5个不同时期和大约500种不同的股票代码进行此计算.这转换为12秒* 5计算* 500符号= 30,000秒或8..33小时.

更新声明:

UPDATE tblStockDataMovingAverages_AAPL JOIN 
(SELECT t1.Sequence,
   (
    SELECT AVG(t2.Close)
        FROM tblStockDataMovingAverages_AAPL AS t2
        WHERE (t1.Sequence - t2.Sequence)BETWEEN 0 AND 7
    )AS "8SMA" 
FROM tblStockDataMovingAverages_AAPL AS t1 
ORDER BY t1.Sequence) AS ma_query 
ON tblStockDataMovingAverages_AAPL.Sequence = ma_query.Sequence  
SET tblStockDataMovingAverages_AAPL.8MA_Price = ma_query.8SMA

表设计:

CREATE TABLE `tblStockDataMovingAverages_AAPL` (
  `Symbol` char(6) NOT NULL DEFAULT '',
  `TradeDate` date NOT NULL DEFAULT '0000-00-00',
  `Sequence` int(11) DEFAULT NULL,
  `Close` decimal(18,5) DEFAULT NULL,
  `200MA_Price` decimal(18,5) DEFAULT NULL,
  `100MA_Price` decimal(18,5) DEFAULT NULL,
  `50MA_Price` decimal(18,5) DEFAULT NULL,
  `20MA_Price` decimal(18,5) DEFAULT NULL,
  `8MA_Price` decimal(18,5) DEFAULT NULL,
  `50_200_Cross` int(5) DEFAULT NULL,
  PRIMARY KEY (`Symbol`,`Sequence`),
  KEY `idxSequnce` (`Sequence`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$

任何有关加强这一过程的帮助都将不胜感激.

选择说明的输出:

id  select_type         table   type    possible_keys   key                 key_len ref     rows    Extra
1   PRIMARY             t1      index   NULL            idxSymbol_Sequnce   11      NULL    5205    Using index; Using filesort
2   DEPENDENT SUBQUERY  t2      ALL     NULL            NULL                NULL    NULL    5271    Using where

解决方法:

这应该更好一点:

update tblStockDataMovingAverages_AAPL
join (
  select t1.sequence as sequence, avg(t2.close) as av
  from tblStockDataMovingAverages_AAPL t1
  join tblStockDataMovingAverages_AAPL t2
  on t2.sequence BETWEEN t1.sequence-7 AND t1.sequence
  group by t1.sequence
) t1 on tblStockDataMovingAverages_AAPL.sequence = t1.sequence
set 8MA_Price = t1.av

关于我的BETWEEN语句:field1 OPERATOR表达式(field2)比ON条件中的表达式(field1,field2)OPERATOR表达式更容易优化.我认为这适用于BETWEEN.

看起来您的查询中的ORDER BY是不必要的,删除它可能会使您的查询速度提高一吨.

如果任何股票代码出现在同一个表中,请将所有这些符号粘贴到单个更新查询中(虽然不同的时间段不起作用),这可能比为每个查询运行它更快.

如前所述,向Close添加索引可能会有所帮助.

标签:mysql,performance,moving-average
来源: https://codeday.me/bug/20190704/1372688.html