0

我有其他人配置的这个查询需要很长时间才能执行,我想知道是否有任何方法可以优化它。

SELECT COUNT( t2.ticker ) /  '99' AS PctNewHigh_Yearlyarray 
FROM (
    SELECT t1.ticker, ROUND( SUM( t1.close ) , 2 ) as DailyChange
    FROM (
        SELECT b.ticker, b.close
        FROM broad b
        WHERE b.Date1 =  '2012-07-30 00:00:00'

        UNION

        SELECT b.ticker, MAX( b.close ) * -1 
        FROM broad b
        WHERE b.Date1 >  '2011-07-31 00:00:00'
        GROUP BY b.Ticker
        ORDER BY ticker
    ) t1 
    GROUP BY t1.ticker
) t2
WHERE DailyChange = 0

数据库结构为:

CREATE TABLE `broad` (
  `idbroad` int(11) NOT NULL AUTO_INCREMENT,
  `Date1` datetime DEFAULT NULL,
  `Date2` varchar(10) DEFAULT NULL,
  `Ticker` varchar(45) DEFAULT NULL,
  `Open` double DEFAULT NULL,
  `High` double DEFAULT NULL,
  `Low` double DEFAULT NULL,
  `Close` double DEFAULT NULL,
  `Vol` double DEFAULT NULL,
  `TC2k_IG` varchar(100) DEFAULT NULL,
  `MS2` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`idbroad`),
  KEY `indx_Date1` (`Date1`),
  KEY `indx_Ticker` (`Ticker`),
  KEY `indx_High` (`High`),
  KEY `indx_Close` (`Close`),
  KEY `indx_TC2k_IG` (`TC2k_IG`),
  KEY `indx_Vol` (`Vol`),
  KEY `indx_Open` (`Open`),
  KEY `indx_Low` (`Low`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

希望您能提供帮助,如果需要更多数据,请告诉我。
所有数据都是股市数据,例如

INSERT INTO `broad` (`idbroad`, `Date1`, `Date2`, `Ticker`, `Open`, `High`, `Low`, `Close`, `Vol`, `TC2k_IG`, `MS2`) VALUES
(726, '2002-10-10 00:00:00', '20021010', 'A', 10.95, 11.13, 10.8, 10.85, 48534, 'EXAMPLE NAME', '');
4

1 回答 1

0

这应该产生相同的结果,但速度更快。

SELECT COUNT( t2.ticker ) /  '99' AS PctNewHigh_Yearlyarray 
FROM (
    SELECT t1.ticker, ROUND( SUM( t1.close ) , 2 ) as DailyChange
    FROM (
        SELECT b.ticker,
        MIN(CASE WHEN b.Date1 > '2011-07-31 00:00:00' THEN b.close * -1 ELSE b.close END) AS close
        FROM broad b
        WHERE b.Date1 >= '2011-07-31 00:00:00'
        GROUP BY b.Ticker
        ORDER BY NULL
    ) t1 
    GROUP BY t1.ticker
) t2
WHERE DailyChange = 0

您应该发布一个EXPLAIN SELECT ...来自(可能是您的和我的)查询,以确定是否使用了以及使用了哪个索引。如果您合并一些索引而不是拥有这么多索引可能会更好。

于 2013-05-24T11:57:37.780 回答