目的取一段时间内 uid 对应消耗,然后划分区间
发现 group by uid返回的数据越多越慢,这个从 SQL 下手有优化空间吗
MySQL 5.7
select
elt(interval(total, null, 300), '-INF~300', '300~INF') as section,
count(*) AS total
from (
select
uid,
SUM(gold) as total
from `table_name`
where `time` > 1640966400 and `time` <= 1642176000 group by `uid`
) as `tmp` group by `section`;
-- 执行了 3-4 秒
返回结果:
-INF~300 46319
300~INF 15060
EXPLAIN 结果:
| select_type | table | type | possible_keys | rows | rows |
|---|---|---|---|---|---|
| PRIMARY | <derived2> | ALL | 217073 | Using temporary; Using filesort | |
| DERIVED | table_name | index | time,uid | 434146 | Using where |