I'm trying to figure our why my query is very slow using MAX, Where and GROUP by.
Table size: 2246096 rows
Indexes:
- created_at_machine_id_idx(created_at,machine_id)
Query:
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`;
Explained:
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 |
It takes now between 3 and 4 seconds. I tried more combinations of indexes but without any luck.
Basically I want to get the last id for each machine lower than 2021-11-14 07:45:00.
id is Primary key.