I want to fetch the N previous weeks of data from my MySQL-table based on the date that’s in the table’s rows.
Imagine that the current week is number 30, and I have rows with data from week 29, 28, 26 and 12.
If I want the last two weeks rows based on todays date, that’s easy, but I want it based on the timestamp on the row.
So if N = 2, I want all rows from week 29 and 28. If N = 3 I want week 29, 28 and 26, no matter which week it is when I’m fetching it.
I could do this using PHP and guessing based on estimated output, but maybe there is some MySQL-functionality I can take advantage of.
One approach is to get the set of weeks you want returned using a query, and then using that query as an inline view which you can join to.
Something like this:
The inline view (aliased as
r) gets a the list of the N latest week values in the table. (This assumes that the week column is sortable, like it would be if it were an integer.That is joined to the table, with the ON clause restricting the rows returned from the table to those rows that have a week value that matches one returned by the inline view.
NOTE: an index on the
weekcolumn may provide significant performance benefit for a large number of rows, and a high cardinality on theweekcolumn.NOTE: With large tables, there can be performance differences between doing a JOIN operation vs using an
IN (subquery)predicate, as the example below. For most large sets, and the queries that I do, I find that the JOIN usually performs better. But you might want to test both, to see which performs better for you. (On small tables, it’s not going to matter much either way; the performance differences become significant on really big tables.)