有人可以在MySQL 8.0.16中为我提供此查询吗?该查询在AWS RDS上无限运行,并耗尽内存,我想问题可能出在UNION ALL和GROUP BY语句上。
SELECT
SUM(`CONV`.`ELEGIVEL`) AS `ELEGIVEL`,
SUM(`CONV`.`ADESAO`) AS `ADESAO`,
`CONV`.`ano` AS `ano`,
`CONV`.`mes` AS `mes`,
`CONV`.`TIPO` AS `TIPO`
FROM
(
SELECT
SUM(`v`.`QuantidadeItem`) AS `ELEGIVEL`,
NULL AS `ADESAO`,
`v`.`ano` AS `ano`,
`v`.`mes` AS `mes`,
'BENCH' AS `TIPO`
FROM
`V_VENDAS_ELEGIVEIS` `v`
WHERE
((`v`.`nome_emp` LIKE '%ESB%')
AND (`v`.`data_lancamento` BETWEEN DATE_FORMAT((NOW() - INTERVAL 12 MONTH), '%Y-%m-01') AND LAST_DAY((CURDATE() - INTERVAL 1 MONTH))))
GROUP BY `v`.`ano` , `v`.`mes` UNION ALL SELECT
NULL AS `ELEGIVEL`,
COUNT(0) AS `ADESAO`,
`V_SEGUROS_ADESAO`.`Ano` AS `ano`,
`V_SEGUROS_ADESAO`.`Mes` AS `mes`,
'BENCH' AS `TIPO`
FROM
`V_SEGUROS_ADESAO`
WHERE
((`V_SEGUROS_ADESAO`.`nome_emp` LIKE '%ESB%')
AND (`V_SEGUROS_ADESAO`.`dataemissao` BETWEEN DATE_FORMAT((NOW() - INTERVAL 12 MONTH), '%Y-%m-01') AND LAST_DAY((CURDATE() - INTERVAL 1 MONTH))))
GROUP BY `V_SEGUROS_ADESAO`.`Ano` , `V_SEGUROS_ADESAO`.`Mes` UNION ALL SELECT
SUM(`v`.`QuantidadeItem`) AS `ELEGIVEL`,
NULL AS `ADESAO`,
`v`.`ano` AS `ano`,
`v`.`mes` AS `mes`,
'BRAND' AS `TIPO`
FROM
`V_VENDAS_ELEGIVEIS` `v`
WHERE
(`v`.`data_lancamento` BETWEEN DATE_FORMAT((NOW() - INTERVAL 12 MONTH), '%Y-%m-01') AND LAST_DAY((CURDATE() - INTERVAL 1 MONTH)))
GROUP BY `v`.`ano` , `v`.`mes` UNION ALL SELECT
NULL AS `ELEGIVEL`,
COUNT(0) AS `ADESAO`,
`V_SEGUROS_ADESAO`.`Ano` AS `ano`,
`V_SEGUROS_ADESAO`.`Mes` AS `mes`,
'BRAND' AS `TIPO`
FROM
`V_SEGUROS_ADESAO`
WHERE
(`V_SEGUROS_ADESAO`.`dataemissao` BETWEEN DATE_FORMAT((NOW() - INTERVAL 12 MONTH), '%Y-%m-01') AND LAST_DAY((CURDATE() - INTERVAL 1 MONTH)))
GROUP BY `V_SEGUROS_ADESAO`.`Ano` , `V_SEGUROS_ADESAO`.`Mes`
) `CONV`
GROUP BY `CONV`.`ano` , `CONV`.`mes`, `CONV`.`TIPO`
如果像下面的代码那样每次将上面的查询拆分为一个查询,则结果很快。
SELECT
SUM(`BENCH`.`ELEGIVEL`) AS `ELEGIVEL`,
SUM(`BENCH`.`ADESAO`) AS `ADESAO`,
`BENCH`.`ano` AS `ano`,
`BENCH`.`mes` AS `mes`,
'BENCHMARK' AS `TIPO`
FROM
(SELECT
SUM(`v`.`QuantidadeItem`) AS `ELEGIVEL`,
NULL AS `ADESAO`,
`v`.`ano` AS `ano`,
`v`.`mes` AS `mes`
FROM
`V_VENDAS_ELEGIVEIS` `v`
WHERE
((`v`.`nome_emp` LIKE '%ESB%')
AND (`v`.`data_lancamento` BETWEEN DATE_FORMAT((NOW() - INTERVAL 12 MONTH), '%Y-%m-01') AND LAST_DAY((CURDATE() - INTERVAL 1 MONTH))))
GROUP BY `v`.`ano` , `v`.`mes` UNION ALL SELECT
NULL AS `ELEGIVEL`,
COUNT(0) AS `ADESAO`,
`V_SEGUROS_ADESAO`.`Ano` AS `ano`,
`V_SEGUROS_ADESAO`.`Mes` AS `mes`
FROM
`V_SEGUROS_ADESAO`
WHERE
((`V_SEGUROS_ADESAO`.`nome_emp` LIKE '%ESB%')
AND (`V_SEGUROS_ADESAO`.`dataemissao` BETWEEN DATE_FORMAT((NOW() - INTERVAL 12 MONTH), '%Y-%m-01') AND LAST_DAY((CURDATE() - INTERVAL 1 MONTH))))
GROUP BY `V_SEGUROS_ADESAO`.`Ano` , `V_SEGUROS_ADESAO`.`Mes`) `BENCH`
GROUP BY `BENCH`.`ano` , `BENCH`.`mes`
该服务器基于AWS RDS。我没有更改任何参数组,它是default.mysql8.0参数。
这是一个db.t3.medium实例,它具有4Gb RAM
嵌套的SELECT语句在每个级别进行分组太复杂且效率低下。我强烈建议您将逻辑重新设计为存储过程,在其中可以使用临时表和更简单的命令的组合来一次收集数据。