MAX

时间:2017-07-26 16:51:58

标签: mysql max

我试图加快目前需要1.2秒才能运行的查询。查询是:

select 
process.exchange,
process.market,
process.volume,
process.bid,
process.ask,
(select MAX(last) FROM a where a.exchange = process.exchange 
AND a.market = process.market 
AND a.created_date > NOW() - INTERVAL 5 MINUTE LIMIT 1) as Ask1,
Ask2,
((Ask2 / (select MAX(last) FROM a where a.exchange = process.exchange 
AND a.market = process.market 
AND a.created_date > NOW() - INTERVAL 5 MINUTE LIMIT 1 ))
 * 100) - 100 as percentage
FROM process
WHERE process.exchange IN('BLAH','BLAH2')
ORDER BY percentage ASC

表格结构:

CREATE TABLE `a` (
  `id` int(10) UNSIGNED NOT NULL,
  `exchange` varchar(15) NOT NULL,
  `market` varchar(15) NOT NULL,
  `volume` double UNSIGNED NOT NULL,
  `bid` double NOT NULL,
  `ask` double UNSIGNED NOT NULL,
  `last` double NOT NULL,
  `created_date` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

ALTER TABLE `a`
  ADD PRIMARY KEY (`id`),
  ADD KEY `market` (`market`),
  ADD KEY `exchange` (`exchange`),
  ADD KEY `created_date` (`created_date`);

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


CREATE TABLE `process` (
  `id` int(11) NOT NULL,
  `exchange` varchar(20) NOT NULL,
  `market` varchar(10) NOT NULL,
  `volume` double NOT NULL,
  `bid` double NOT NULL,
  `ask` double NOT NULL,
  `Ask2` double NOT NULL,
  `created_date` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

ALTER TABLE `process`
  ADD PRIMARY KEY (`id`),
  ADD KEY `created_date` (`created_date`),
  ADD KEY `exchange` (`exchange`),
  ADD KEY `market` (`market`);

ALTER TABLE `process`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

我需要计算Ask1Ask2之间的百分比变化。 Ask1信息在另一个名为a的表中,每个市场和交易所都有很多行价格。

这就是表格中的数据" a"看起来像:

Exchange  Market Volume Bid Ask Last Created Date
BLAH      APL      3000 1.2 1.3 1.3  2017-07-26 16:31:00
BLAH      APL      3000 1.4 1.5 1.45 2017-07-26 16:30:00

我需要Ask1从这里获取最近5分钟内获得最高价值的信息。所以我得到的子查询是:

select MAX(last) 
  FROM a 
 where a.exchange = process.exchange 
   AND a.market = process.market 
   AND a.created_date > NOW() - INTERVAL 5 MINUTE 
 LIMIT 1

我需要选择它并使用它进行计算,所以目前我必须有两次子查询。

MAX似乎会大大减慢子查询的速度。

这就是EXPLAIN所说的:

id select type table   partitions type  possible keys key  key_len ref  rows filtered Extra
1 PRIMARY     process NULL       ALL   exchange      NULL NULL    NULL 272 99.63 Using where; Using temporary; Using filesort
2 DEPENDENT SUBQUERY a NULL      ref   market,exchange,created_date market 47 cms.process.market 1603 0.17 Using index condition; Using where
3 DEPENDENT SUBQUERY a NULL      ref   market,exchange,created_date market 47 cms.process.market 1603 0.17 Using index condition; Using where

" a"表有大约一百万行和"进程"表有大约630行。

是否有可能加快速度?

提前感谢您的帮助。

0 个答案:

没有答案