请帮我优化下这段代码(insert into table ccic_fkyjrisk.tradeRiskComputeResult_31_61 SELECT 'T0082',a.policyID,a.customercode,cast(1 as DECIMAL(18,4)) FROM ccic_fkyjrisk.FocusCustomerPolicyData a JOIN ch_zyy.E_INTEL_RM_CP_T_PA_PL_BOND_POL_LOB b on a.POLICYID = b.POLICY_ID where b.RISK_LEVEL_CODE in ('10','5') and a.firstInsuranceCode = '30000' and a.secondInsuranceCode = '31000_2' union all SELECT 'T0082',a.policyID,a.customercode,cast(1 as DECIMAL(18,4)) FROM ccic_fkyjrisk.FocusCustomerPolicyData a JOIN ch_zyy.E_INTEL_RM_CP_T_PA_PL_ENG_DTL b on a.POLICYID = b.POLICY_ID where b.RISK_LEVEL_CODE in ('4','5') or left(b.RISK_LEVEL_CODE,2) in ('04','05') and a.firstInsuranceCode = '30000' and a.secondInsuranceCode = '31000_2';)
时间: 2024-03-08 20:46:49 浏览: 73
可以考虑如下优化:
1. 使用 EXISTS 替代 JOIN 操作,避免 JOIN 过程中的冗余计算。
2. 将 WHERE 中的 OR 和 IN 子句转换为多个条件的 AND 子句,这样可以避免使用 OR 或 IN 时造成的索引失效和性能下降。
3. 考虑对需要连接的表添加索引,以提高查询效率。
4. 对于需要插入的表,可以先对其进行分区,可以提高插入效率。
优化后的代码如下:
```sql
INSERT INTO ccic_fkyjrisk.tradeRiskComputeResult_31_61
PARTITION (partition_name)
SELECT 'T0082',
a.policyID,
a.customercode,
CAST(1 AS DECIMAL(18, 4))
FROM ccic_fkyjrisk.FocusCustomerPolicyData a
WHERE a.firstInsuranceCode = '30000'
AND a.secondInsuranceCode = '31000_2'
AND EXISTS
(SELECT 1
FROM ch_zyy.E_INTEL_RM_CP_T_PA_PL_BOND_POL_LOB b
WHERE a.POLICYID = b.POLICY_ID
AND b.RISK_LEVEL_CODE IN ('10', '5'))
UNION ALL
SELECT 'T0082',
a.policyID,
a.customercode,
CAST(1 AS DECIMAL(18, 4))
FROM ccic_fkyjrisk.FocusCustomerPolicyData a
WHERE a.firstInsuranceCode = '30000'
AND a.secondInsuranceCode = '31000_2'
AND EXISTS
(SELECT 1
FROM ch_zyy.E_INTEL_RM_CP_T_PA_PL_ENG_DTL b
WHERE a.POLICYID = b.POLICY_ID
AND (b.RISK_LEVEL_CODE IN ('4', '5') OR LEFT(b.RISK_LEVEL_CODE, 2) IN ('04', '05')));
```
需要注意的是,需要将 `partition_name` 替换为实际的分区名称。
阅读全文