Mysql 索引不适用于单个 Group By

标签 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)

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

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

最佳答案

我假设您想要对 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,这应该是性能上的胜利。

关于Mysql 索引不适用于单个 Group By,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58140556/

相关文章:

php - 与 PHP 更新用户的斗争

PHP/MySQL 大插入

Java 字符串到整数不起作用?

SQL:列上的外键指向同一列

php - MySQL:索引附加字段的缺点是什么?

mysql - 如何使用 mysql 即可编辑数据网格在 wpf 数据网格本身中插入更新删除

c# - 在没有主键的实体中使用表(使用实体代码优先迁移)

mysql - 如何使用mysql更新同一个表中的值?

javascript - 是否有类似 Solr 或 Elasticsearch 的东西只能在 Javascript 中在客户端上使用?

r - 按时间和 id r 传播字符列