我有一个如下查询:
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/