I need to get certain tracked data, including a couple of max and mins. I already have a horrible way to do it below, but as you know this is REALLY slow because i’m using subqueries and the table has a couple of thousands of rows. Specifically I need to get a different MAX values per row, depending on the type_dev of the current row. with 24000 records it becomes unusable, and I think is even slower when I try with MAX clauses instead.
SELECT dt.some_data, dt.date_visit, dt.url,
(SELECT date_visit FROM device_tracker
WHERE type_dev = dt.type_dev ORDER BY date_visit DESC LIMIT 1) last_visit,
(SELECT date_visit FROM device_tracker
WHERE type_dev = dt.type_dev and url = dt.url ORDER BY date_visit DESC LIMIT 1) last_visit_to_this_url
FROM device_tracker dt WHERE some_where_clauses;
Please note that I don’t need global max values (it could be really easy), but for example in this case I’m getting the max date of every single type_dev (every row can be a different type or not) and also the max date of a certain url regarding each row.
I Need the same with the minimun dates.
For sure there are a lot of nicer ways to do it. Could anyone throw some light on it?
Create a composite index on
(type_dev, url, date_visit)for this to work fast.