首先,这个查询在单个数据库中运行良好但是当我在其中使用不同的数据库(product和pms_history)时,它开始花费几分钟来执行。
SELECT SUM(ppi.`key_closing_balance`) FROM `pms_history`.`pool_product_income` ppi,`pms`.product p
WHERE ppi.`pool_id`=$P{poolId} AND ppi.`product_id`=p.`id`
AND ((p.`line` BETWEEN 155 AND 460) OR (p.`line`=2855)) AND p.`account_type`='PL'
UNION ALL
SELECT SUM(ppi.`key_closing_balance`) FROM pms_history.`pool_product_income` ppi,pms.product p
WHERE ppi.`pool_id`=$P{poolId} AND ppi.`product_id`=p.`id`
AND ((p.`line`=35)) AND p.`account_type`='PL'
UNION ALL
SELECT SUM(ppi.`key_closing_balance`) FROM pms_history.`pool_product_income` ppi,pms.product p
WHERE ppi.`pool_id`=$P{poolId} AND ppi.`product_id`=p.`id`
AND ((p.`line`=39)) AND p.`account_type`='PL'
UNION ALL
SELECT SUM(ppi.`key_closing_balance`) FROM pms_history.`pool_product_income` ppi,pms.product p
WHERE ppi.`pool_id`=$P{poolId} AND ppi.`product_id`=p.`id`
AND ((p.`line` BETWEEN 705 AND 715)) AND p.`account_type`='PL'
UNION ALL
SELECT SUM(ppi.`key_closing_balance`) FROM pms_history.`pool_product_income` ppi,pms.product p
WHERE ppi.`pool_id`=$P{poolId} AND ppi.`product_id`=p.`id`
AND ((p.`line` BETWEEN 60 AND 124 ) OR (p.`line` BETWEEN 2195 AND 2225)) AND p.`account_type`='PL';
答案 0 :(得分:2)
使用case
表达式进行条件聚合。然后,您可以在没有UNION ALL
:
SELECT SUM(case when (p.`line` BETWEEN 155 AND 460) OR (p.`line`=2855) then ppi.`key_closing_balance` end),
SUM(case when (p.`line` = 35) then ppi.`key_closing_balance` end),
SUM(case when (p.`line` = 39) then ppi.`key_closing_balance` end),
SUM(case when (p.`line` BETWEEN 705 AND 715) then ppi.`key_closing_balance` end),
SUM(case when (p.`line` BETWEEN 60 AND 124 ) OR (p.`line` BETWEEN 2195 AND 2225) then ppi.`key_closing_balance` end)
FROM `pms_history`.`pool_product_income` ppi
JOIN `pms`.product p ON ppi.`product_id` = p.`id`
WHERE ppi.`pool_id` = $P{poolId}
AND p.`account_type` = 'PL'
还切换到现代的,明确的JOIN
语法。