简体   繁体   English

使用AVG()优化查询并在一张大桌子上分组?

[英]Optimize query with AVG() and group by on a big table?

I am wondering if there is a way to optimize this query: 我想知道是否有一种方法可以优化此查询:

SELECT Avg(selloff1), 
       YEAR(dt), 
       weekno 
FROM   bbproduct 
GROUP  BY YEAR(dt), 
          weekno 

Table schema is: 表模式是:

CREATE TABLE `bbproduct` (
 `id` bigint(20) NOT NULL,
 `CUSTNO` decimal(6,0) unsigned zerofill NOT NULL default '000000',
 `DEPTNO` decimal(1,0) unsigned zerofill NOT NULL default '0',
 `PRODNO` decimal(4,0) unsigned zerofill NOT NULL default '0000',
 `DT` date NOT NULL,
 `ARDATE8N` decimal(8,0) unsigned zerofill NOT NULL default '00000000',
 `STORENO` char(6) NOT NULL default '0',
 `DAYCODE` decimal(1,0) unsigned zerofill NOT NULL default '0',
 `WEEKNO` decimal(2,0) unsigned zerofill NOT NULL default '00',
 `WKOFMONTH` decimal(2,0) unsigned zerofill NOT NULL default '00',
 `QUANTITY` decimal(7,0) NOT NULL default '0',
 `CARRYOVER` decimal(7,0) NOT NULL default '0',
 `SELLOFF1` decimal(7,0) NOT NULL default '0',
 `ONHANDQTY` decimal(7,0) NOT NULL default '0',
 `KNOWNLOSS` decimal(7,0) NOT NULL default '0',
 `ORDER` decimal(7,0) NOT NULL default '0',
 `FAMLYCD` decimal(4,0) NOT NULL default '0',
 `ROUTENO` decimal(4,0) NOT NULL default '0',
 `AGENCYNO3N` decimal(3,0) NOT NULL default '0',
 `RETURNS` decimal(7,0) NOT NULL,
 `LASTUPDATE` datetime NOT NULL,
 PRIMARY KEY  (`CUSTNO`,`DEPTNO`,`PRODNO`,`DT`),
 KEY `in_bbproduct_custnodeptnoprodno` (`CUSTNO`,`DEPTNO`,`PRODNO`),
 KEY `in_bbproduct_deptnocustno` USING BTREE (`DEPTNO`,`CUSTNO`),
 KEY `in_bbproduct_custno` USING BTREE (`CUSTNO`),
 KEY `in_bbproduct_dt` USING BTREE (`DT`),
 KEY `in_bbproduct_routeno` (`ROUTENO`),
 KEY `in_bbproduct_selloff1` (`SELLOFF1`),
 KEY `in_bbproduct_weekno` (`WEEKNO`),
 KEY `in_bbproduct_routenoweekno` (`WEEKNO`,`ROUTENO`),
 KEY `in_bbproduct_agencyroutedt` USING BTREE (`AGENCYNO3N`,`ROUTENO`,`DT`),
 KEY `in_bbproduct_routenoagencyno3n` (`ROUTENO`,`AGENCYNO3N`),
 KEY `in_bbproduct_agencyno` (`AGENCYNO3N`),
 KEY `in_bbproduct_storeno_prodno` (`STORENO`,`PRODNO`),
 KEY `ind_deptno_prodno` (`DEPTNO`,`PRODNO`),
 KEY `ind_prodno` (`PRODNO`),
 KEY `ind_dt_custno_deptno_prodno` (`DT`,`CUSTNO`,`DEPTNO`,`PRODNO`),
 KEY `ind_dt_selloff1` (`DT`,`SELLOFF1`)
) ENGINE=MyISAM AUTO_INCREMENT=9300871 DEFAULT CHARSET=latin1

It takes 14 seconds, table has 9 millions of records, and query returns 15 rows. 它需要14秒,表有9百万条记录,查询返回15行。 I will need to join this result set with some other records. 我将需要将此结果集与其他一些记录一起加入。

Can I do something more? 我还能做点什么吗?

Since you are grouping by year and week number, I presume that most of the data will not change more than weekly. 由于您是按年和周编号分组的,因此我认为大多数数据的变化不会超过每周。 You can cache the result in another table that can be updated in batch only one time per week. 您可以将结果缓存在另一个表中,该表每周只能一次批量更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM