- rds数据库(mysql的一种),recode_table表记录数5亿,org_table表记录数4万
- 原执行速度超时(60秒以上)
SELECT cu.org_no as orgNo,
org.org_short_name as orgName,
round(sum(qty) /10000, 2) as aValue,
cast(round((sum(qty) -sum(qty_corrprd)) / sum(qty_corrprd) *100, 2) as decimal(22, 2)) as cValue
FROM `org_table` org
left join recode_table cu on cu.org_no= org.org_no
and cu.time_period= '01'
and cu.ind_cls in ('0101', '0202', '0303')
and cu.stat_date between '20240801'
and '20240810'
where org.prnt_org_no= '11101'
group by org.org_no,
org.org_name,
org.org_short_name
SELECT cu.org_no as orgNo,
org.org_short_name as orgName,
round(sum(qty) /10000, 2) as aValue,
cast(round((sum(qty) -sum(qty_corrprd)) / sum(qty_corrprd) *100, 2) as decimal(22, 2)) as cValue
from org_table org
left join(
select cu.org_no, qty, qty_corrprd
from recode_table cu
where cu.time_period= '01'
and cu.ind_cls in('0101', '0202', '0303')
and cu.stat_date between '20240801'
and '20240810'
) cu on cu.org_no= org.org_no
where org.prnt_org_no= '11101'
group by org.org_no,
org.org_name,
org.org_short_name
- 解决方式一:把条件都放到where中,执行速度2.5s
SELECT cu.org_no as orgNo,
org.org_short_name as orgName,
round(sum(qty) /10000, 2) as aValue,
cast(round((sum(qty) -sum(qty_corrprd)) / sum(qty_corrprd) *100, 2) as decimal(22, 2)) as cValue
FROM `org_table` org
join recode_table cu on cu.org_no= org.org_no
where cu.time_period= '01'
and cu.ind_cls in('0101', '0202', '0303')
and cu.stat_date between '20240801'
and '20240810'
and org.prnt_org_no= '11101'
group by org.org_no,
org.org_name,
org.org_short_name
- 解决方式二:把条件都放到where中,同时外层再重复关联org_table表执行速度2.5s
select org.org_no as orgNo,
org.org_short_name as orgName,
a.aValue as aValue,
a.cValue as cValue
FROM org_table org
left join
(
SELECT cu.org_no as orgNo,
org.org_short_name as orgName,
round(sum(qty) /10000, 2) as aValue,
cast(round((sum(qty) -sum(qty_corrprd)) / sum(qty_corrprd) *100, 2) as decimal(22, 2)) as cValue
FROM `org_table` org
inner join recode_table cu on cu.org_no= org.org_no
where cu.time_period= '01'
and cu.ind_cls in ('0101', '0202', '0303')
and cu.stat_date between '20240801'
and '20240810'
and org.prnt_org_no= '11101'
group by org.org_no,
org.org_name,
org.org_short_name
) as a on a.orgNo= org.org_no
where org.prnt_org_no= '11101'
- 解决方法三:使用union 强制让子查询走索引,执行速度0.2s
SELECT cu.org_no as orgNo,
org.org_short_name as orgName,
round(sum(qty) /10000, 2) as aValue,
cast(round((sum(qty) -sum(qty_corrprd)) / sum(qty_corrprd) *100, 2) as decimal(22, 2)) as cValue
from org_table org
left join(
select cu.org_no, qty, qty_corrprd
from recode_table cu
where cu.time_period= '01'
and cu.ind_cls in('0101', '0202', '0303')
and cu.stat_date between '20240801'
and '20240810'
union
select null,null,null
) cu on cu.org_no= org.org_no
where org.prnt_org_no= '11101'
group by org.org_no,
org.org_name,
org.org_short_name