左关联不走索引的问题
公司用的flow able工作流,最近做了个需求需要在列表查询中查到这个流程的下一节点审核岗位和审核人,因为要关联流程表,所以我希望一次查出来.于是我写了如下的Sql
下面展示一些 内联代码片
。
select
r.id,
r.shop_code,
r.shop_name,
r.fran_code,
r.fran_name,
r.start_date,
r.end_date,
r.contract_status,
r.contract_type,
r.contract_no,
r.new_contract_no,
r.level_2,
r.level2_name,
r.contract_file_path,
r.margin_total,
r.partya_contact,
r.contact_information,
r.position,
r.remark,
r.verify_id,
r.del_flag,
r.create_time,
r.update_time,
r.create_by,
r.update_by,
hcr.monthly_money as monthly_rent,
hcr.monthly_commission,
hcr.sales,
hcr.commission_rent,
v.process_ins_id,
ac.name_ as next_handle_job,
u.name as next_handle_person,
(select sum(monthly_money) from t_house_contract_property_costs co WHERE r.id=co.contract_id and co.del_flag=0
and co.type = 'month' and DATE_FORMAT(co.start_date,'%Y-%m')= '2020-08' limit 1) monthly_property_costs,
(select sum(monthly_money) from t_house_contract_margin ma WHERE r.id=ma.contract_id and ma.del_flag=0 and
ma.type = 'month' and ma.month= '2020-08' limit 1) other_money
from t_house_rental_contract_refactor r
left join (select sum(re.monthly_money) as monthly_money, contract_id,
re.monthly_commission,re.sales,re.commission_rent from t_house_contract_rent re where re.del_flag = '0'
and DATE_FORMAT( re.start_date, '%Y-%m' )= '2020-08' AND type = 'month' GROUP BY
re.contract_id ) hcr on hcr.contract_id = r.id
left join t_verify v on (r.verify_id = v.id and v.del_flag='0')
left join act_ru_task ac on ac.proc_inst_id_ = v.process_ins_id
left join t_user u on u.id = ac.assignee_
where r.del_flag = '0'
自信的我以为线上的主表不过几千条数据,于是就没有用线上数据测试,但是上线哪天很不幸,这个Sql执行超时了,诧异的我只能用EXPLAIN看看执行计划
很明显,主表和t_user表都全表扫描了,我心想,不应该啊,左关联t_user表,on后面用的是主键做条件,为什么不走索引呢?
百度一番,才明白原来关联字段的字符解析集不一致,不会走索引.于是我把t_user表的字符解析集改为和act_ru_task表一致,再次查询,有了如下的执行计划
可以看到左关联的t_user表走了索引.
但是最终我没有改t_user表的字符解析集,因为我觉得关联多张表查询确实影响效率,索性就没有关联t_user表,而是,查询出所有用户后,放到Map中,获取对应的用户名.
加油(ง •_•)ง,我是一个在学习路上砥砺前行的小菜鸟.