I have a medium-large table (around 350000 entries and growing up). I need to fetch each last entry for the pair dev_id and var_id from the table. I actually I can fetch them, but the query takes around 20 seconds, and that it's unacceptable for my purposes.
I'm trying the next query on a MySQL server with MariaDB:
select d.dev_id, d.var_id, d.ts, d.value from data_table d
where d.ts > NOW() - INTERVAL 2 DAY
and ts = (SELECT MAX(ts) FROM data_table
WHERE dev_id = d.dev_id
AND var_id = d.var_id)
ORDER BY d.dev_id
The table has a structure like down below:
id | dev_id | frame_number | var_id | value | ts
1 | 2 | 1 | 2 | 65.5 | 2019-10-10 19:56:05
2 | 3 | 5 | 4 | 23 | 2019-10-10 20:56:06
3 | 2 | 1 | 2 | 65.5 | 2019-10-10 20:59:30
. | . | . | . | . | .
. | . | . | . | . | .
. | . | . | . | . | .
300k| 5 | 100 | 7 | -15.23| 2020-10-10 20:59:30
I need to get a faster response for a similar query, but my experience is not enough to detect the bottleneck in the query
EDIT 1: I cant ommit the ORDER BY but the improvement ommiting that is low (20 seconds versus 18.5 seconds)
EDIT 3 and how to fix it: Added (dev_id, var_id and ts) as index (index based on multiple columns). The query now only needs 0.6 seconds