为什么这个查询花了这么多时间来执行?

时间:2017-08-20 16:56:48

标签: mysql sql query-performance

有没有更好的方法来写这个?

select Date, NeName, KPINAME, SUB_TYPE1, KPI 
from ggsn_kpi_2017 
where date 
    in ('2017-08-19', '2017-08-18', '2017-08-17', '2017-08-16', '2017-08-15', 
    '2017-08-14', '2017-08-13') 
    and KPINAME in('SM_SUCC_SESS_ACT_GGSN', 'SM_FAIL_SESS_ACT_GGSN', 'SM_SUCC_SESS_ACT_P_GW', 'SM_FAIL_SESS_ACT_P_GW', 
    'SM_SUCC_SESS_ACT_SAE_GW', 'SM_FAIL_SESS_ACT_SAE_GW', 
    'SM_DOWNLINK_BYTES_M2M', 'SM_UPLINK_BYTES_M2M') 

    group by Date, NeName, KPINAME 

    union 

    select Date, NeName, KPINAME, SUB_TYPE1, KPI 
    from ggsn_kpi_2016 
    where date in ('2017-08-19', '2017-08-18', '2017-08-17', '2017-08-16', 
    '2017-08-15', '2017-08-14', '2017-08-13') 
    and KPINAME in('SM_SUCC_SESS_ACT_GGSN', 'SM_FAIL_SESS_ACT_GGSN', 'SM_SUCC_SESS_ACT_P_GW', 
    'SM_FAIL_SESS_ACT_P_GW', 'SM_SUCC_SESS_ACT_SAE_GW', 
    'SM_FAIL_SESS_ACT_SAE_GW', 'SM_DOWNLINK_BYTES_M2M', 'SM_UPLINK_BYTES_M2M') 
    group by Date, NeName, KPINAME;

1 个答案:

答案 0 :(得分:0)

此查询中有一个明显的性能反模式。

where date in ('2017-08-19', '2017-08-18', '2017-08-17', '2017-08-16', 
'2017-08-15', '2017-08-14', '2017-08-13')

如果dateDATETIMETIMESTAMPDATE列,请将其更改为

where date >= '2017-08-13'
  and date <  '2017-08-20'

甚至

where date >= '2017-08-13'
  and date <  '2017-08-13' + INTERVAL 1 WEEK

然后在(date, KPINAME)上为两个表创建索引。这将使您的WHERE条款至少部分sargable

此外,您似乎在滥用GROUP BY。这与MAX()AVG()等聚合函数有关。你的意思是ORDER BY