SQL优化:

今日给人查找数据,时间关系,写个比较粗暴的SQL语句:

 

 
#2s587ms
#直接将所有表关联,比较粗暴
select go.businessId,dd.dict_namefrom fn_xte.gte_order go,fn_config.t_dictionary_type dt,fn_config.t_dictionary_dict dd

where go.appId = dt.app_id and dt.data_key = dd.dict_type and dict_code = go.xingZhenQuYu and dt.data_key_name = 'XING_ZHENG_QU_YU' 

此条语句对三个表进行关联,递归层次较深,产生的计算量就会很大,平均为X^3级别。然后根据where语句对关联的结果集进行筛选。耗时操作主要是在from子句中的三个表的联合操作。

所以用子查询对其进行优化为:

#487ms
#首先fn_xte.gte_order,fn_config.t_dictionary_type进行联合,fn_config.t_dictionary_type在后,作为驱动表,根据app_Id,在fn_xte.gte_orde进行查询,利用索引
select temp.businessId,dd.dict_name
from fn_config.t_dictionary_dict dd,(select go.businessId,go.xingZhenQuYu,dt.data_key
  from fn_xte.gte_order go,fn_config.t_dictionary_type dt
where dt.app_id = go.appId and dt.data_key_name = 'XING_ZHENG_QU_YU') as temp
where dd.dict_type = temp.data_key and dd.dict_code = temp.xingZhenQuYu;

 

进一步优化是关于from,where子句的执行顺序的,这里尚有疑问,待论证:

#405ms
#首先是fn_config.t_dictionary_type dt,fn_xte.gte_order go的联合,fn_xte.gte_order go在后作为驱动,其字段appId有索引,此处我认为索引并未有作用
#因为是根据appId查询其他表的,然而结果却表明时间消耗少了,
#可能原因是,表fn_config.t_dictionary_type由于数据太少,冲淡了fn_xte.gte_order索引带来的好处
explain select temp.businessId,dd.dict_name
from (select go.businessId,go.xingZhenQuYu,dt.data_key
 from fn_config.t_dictionary_type dt,fn_xte.gte_order go
where dt.data_key_name = 'XING_ZHENG_QU_YU' and dt.app_id = go.appId) as temp,fn_config.t_dictionary_dict dd
where dd.dict_code = temp.xingZhenQuYu and dd.dict_type = temp.data_key;

 

posted @ 2018-08-15 21:58  流沙若水  阅读(139)  评论(0编辑  收藏  举报