【发布时间】:2021-12-26 03:03:40
【问题描述】:
我试图弄清楚为什么我的查询使用 MAX、Where 和 GROUP by 非常慢。
表格大小:2246096 行
索引:
- created_at_machine_id_idx(created_at,machine_id)
查询:
select
MAX(id) AS id
,machine_id
FROM `table`
WHERE `table`.`machine_id` IN (30, 31, 43, 44, 46, 50, 51, 53, 55, 56...)
AND `created_at` <= '2021-11-14 07:45:00'
GROUP BY `machine_id`;
解释:
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
|---|---|---|---|---|---|---|---|---|---|
| 1 | SIMPLE | table | range | created_at_machine_id_idx | created_at_machine_id_idx | 13 | NULL | 1123048 | Using where; Using index; Using temporary; Using filesort |
现在需要 3 到 4 秒。我尝试了更多的索引组合,但没有任何运气。
基本上我想得到低于 2021-11-14 07:45:00 的每台机器的最后一个 id。
id 是主键。
【问题讨论】:
-
IN中有多少个machine_id?
标签: mysql performance query-optimization