背景
最近项目中有个查询接口非常慢 ,该SQL是主表left join了两张表,主表和另外两张表中都有可能作为查询条件的字段,当另外两张表的字段没有作为筛选条件时,查询效率非常慢,于是做了以下优化。
优化前:
select s.contract_no,
s.plan_no,
s.box_shape_num,
s.customer_name,
s.countries_code,
s.countries_name,
s.total_volume,
s.total_gross_weight,
s.factory_approval_state
from standard_scheme s
left join standard_scheme_material s3 on s3.standard_scheme_id = s.plan_no
LEFT JOIN act_order_special_cnt aos ON aos.special_cnt_cdoe = s.plan_no
<where>
<if test="vo.planNo != null and vo.planNo != '' ">
and s.plan_no like concat('%',#{vo.planNo},'%')
</if>
<if test="vo.materialCode != null and vo.materialCode != '' ">
and s3.material_code = #{vo.materialCode}
</if>
<if test="vo.orderCode != null and vo.orderCode != '' ">
AND aos.order_id = #{vo.orderCode}
</if>
</where>
GROUP BY s.plan_no
ORDER BY s.create_time DESC
优化后:
select s.contract_no,
s.plan_no,
s.box_shape_num,
s.customer_name,
s.countries_code,
s.countries_name,
s.total_volume, s.total_gross_weight,
s.factory_approval_state
from standard_scheme s
<where>
<if test="vo.planNo != null and vo.planNo != '' ">
and s.plan_no like concat('%',#{vo.planNo},'%')
</if>
<if test="vo.materialCode != null and vo.materialCode != '' ">
and s.plan_no in (
SELECT standard_scheme_id
FROM standard_scheme_material
where material_code = #{vo.materialCode}
)
</if>
<if test="vo.orderCode != null and vo.orderCode != '' ">
and s.plan_no in (
SELECT special_cnt_cdoe
FROM act_order_special_cnt
where order_id = #{vo.orderCode}
)
</if>
</where>
GROUP BY s.plan_no
ORDER BY s.create_time DESC