Mysql索引不适用于单个分组依据

时间:2019-09-27 19:44:31

标签: mysql sql indexing

我有一个如下查询:

select s.org_id
     , s.report_date
     , s.country
     , sum(s.number_of_event) as numberOfEvent ...
     , (CASE ce.policy WHEN 1 then ce.custom_revenue else s.revenue END)
  from summary s 
  left join event ce  
    on ce.event_name = s.event_name 
   and s.account_id = ce.account_id 
   and s.app_id = ce.app_id 
 group 
    by s.org_id
     , s.report_date
     , s.country

我的索引是: 摘要:

 1. index(org_id, report_date, country)
 2. index(account_id, app_id, event_name)

对于事件:

 1. index(account_id, app_id, event_name)

当我用explain命令调用sql查询时,它给了我; “使用临时文件排序”

如何为两个表正确使用索引?

1 个答案:

答案 0 :(得分:1)

我将假设您要计算events表中的事件。这很有道理,尽管这不是您的查询正在做的事情。

如果(org_id, report_date, country)summary中是唯一的,您可能会发现这样做更快:

select s.org_id, s.report_date, s.country,
       (select count(*)
        from event e
        where ce.event_name = s.event_name and
              ce.account_id = s.account_id and
              ce.app_id = s.app_id 
       ) as numberOfEvent 
from summary s ;

特别是,您希望在event(event_name, account_id, app_id)上建立索引。

这消除了外部group by,这应该是性能上的胜利。