I have a table which contains data recorded every minute, so I have a row for each minute. When returning the data for processing, this accuracy is required for the last 6 hours but after that, a lower level of accuracy is sufficient, e.g. every 5 minutes.
I can return all the data into an array and then remove all but every 5th element but that requires all data to returned by MySQL and then read into the array first - quite a lot of data.
How can I return every nth row in MySQL? I have read this blog post which suggests using primaryKey % 5 = 0 where primaryKey is auto_increment but this
a) doesn't use indexes b) will only return primaryKey values which are divisible by 5 and in the case of deletions, may not actually be every 5th row
Can this be done just within the SQL query or will it require looping row by row through the result set using cursors?
I am using MySQLi in PHP to connect to the DB.
The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause. SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query.
SELECT * FROM <TableName>; This SQL query will select all columns and all rows from the table. For example: SELECT * FROM [Person].
The NTH_VALUE() is a window function that allows you to get a value from the Nth row in an ordered set of rows. The NTH_VALUE() function returns the value of expression from the Nth row of the window frame. If that Nth row does not exist, the function returns NULL . N must be a positive integer e.g., 1, 2, and 3.
The list of timestamps every 5 minutes:
SELECT
MIN(logtimestamp) AS first_of_five_minutes
FROM tLog
GROUP BY
DATE(logtimestamp),
HOUR(logtimestamp),
MINUTE(logtimestamp) - (MINUTE(logtimestamp) % 5)
Now, you can use this as a sub-select to get the requested log entries by joining logtimestamps
to first_of_five_minutes
on the . Of course, additional WHERE
-clauses have to be replicated inside and outside so you get the "right" timestamps.
Also, note that this returns the first timestamp in every five-minute interval, wheras solutions directly using minutes%5 = 0
only return logentries which are actually on multiples of :05, which may fail if you have delays in recording logs or similar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With