Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get every n rows in MySQL?

Tags:

php

mysql

mysqli

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.

like image 370
davidmytton Avatar asked Feb 02 '09 10:02

davidmytton


People also ask

How do I get 10 rows in MySQL?

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.

How do I select all rows in SQL?

SELECT * FROM <TableName>; This SQL query will select all columns and all rows from the table. For example: SELECT * FROM [Person].

How do you find the nth value in MySQL?

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.


1 Answers

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.

like image 76
David Schmitt Avatar answered Oct 05 '22 21:10

David Schmitt