使用count distinct时,存储过程非常缓慢

时间:2016-08-15 02:19:14

标签: mysql

当我第一次运行存储过程时,它是如此缓慢,过程持续1分钟,然后我再次运行它持续10秒。

以下是我的主要sql声明,请帮我看看,非常感谢!

示例1

SELECT sql_no_cache view_address.is_facility,count(DISTINCT 
view_address.provider_id)as totalCount FROM pv_mview_provider_address view_address WHERE
view_address.network_group_id=5047 AND view_address.carrier_group_id=93 GROUP BY
view_address.is_facility;

解释

示例2:

SELECT SQL_NO_CACHE is_facility,count(distinct provider_id) FROM (SELECT 
view_address.provider_id,view_address.is_facility FROM pv_mview_provider_address
view_address WHERE view_address.network_group_id=5047 AND view_address.carrier_group_id=93
) as p GROUP BY is_facility

解释

这个sql将花费10秒来加载数据。 该表存储了4000,0000行。 非常感谢你!

1 个答案:

答案 0 :(得分:1)

对于此查询:

select sql_no_cache a.is_facility,
       count(distinct a.provider_id) as totalCount
from pv_mview_provider_address a
where a.network_group_id = 5047 and
      a.carrier_group_id = 93
group by a.is_facility;

你想要一个索引。最佳指数是pv_mview_provider_address(network_group_id, carrier_group_id, is_facility)。但是,如果from子句中的引用是视图而不是表,那么您需要弄清楚视图中发生了什么。