I’m trying to come up with a MySQL query to select the last record from each of the previous 7 days. If 1 of the previous 7 days is missing data, I would only get back 6 records. Here’s what I have:
SELECT tracking.* FROM tracking
INNER JOIN
(SELECT MAX(lastChecked) AS maxLastChecked, id FROM tracking
WHERE lastChecked >= DATE_SUB(lastChecked, INTERVAL 7 DAY )
GROUP BY DAY(lastChecked)) as Lookup ON Lookup.id = tracking.id
WHERE tracking.propertyID = 1 ORDER BY tracking.lastChecked ASC LIMIT 7
Basically what this should do is select the final recorded entry for propertyID = 1 in the tracking table for each of the past 7 days (starting on today). However, this query is returning this to me (more than ONLY records within the last 7 days):
ID propertyID lastChecked value
2 1 2012-01-25 05:30:00 280
1 1 2012-01-26 12:34:02 268
5 1 2012-01-27 09:51:31 268
83 1 2012-02-13 00:01:07 276
Any help to fix this up would be greatly appreciated!
Try this query: