如何让GROUP BY强制使用索引?

问题描述 投票:0回答:1

我有以下疑问:

SELECT user_id,
       type,
       cast(created_at as date) AS created_at,
       sum(credit) AS credit
FROM wallets_transactions
GROUP BY user_id, type, cast(created_at as date)

大约需要

7
秒才能执行:

enter image description here

另外,我还有这个索引:

wallets_transactions(user_id, type, created_at)

就有了

EXPLAIN
的结果:

enter image description here

看起来像全扫描。知道如何使其更加优化吗?

sql mysql performance indexing
1个回答
0
投票

您的查询必须检查表的所有行。也就是说,没有

WHERE
子句来减少行数。所以它肯定是一个表扫描。

另一种方法是将求和结果缓存在某种汇总表中。这是改进聚合查询的一种非常常见的方法。

一些数据仓库实现在内部执行此操作;预先计算大行块的聚合,因此可以快速组合它们,而无需检查每一行。

© www.soinside.com 2019 - 2024. All rights reserved.