1

I have a MySQL-table of values with 10.000+ records collected from a datalogging device. The table has the following columns:

–––––––––––––––––––––––––––––– | ID | Time | par1 | par2 | –––––––––––––––––––––––––––––– | 0 | .. | .. | .. | –––––––––––––––––––––––––––––– | 1 | .. | .. | .. | –––––––––––––––––––––––––––––– 

.. and so on.

The ID is auto-incrementing. I would like to query the table for values to plot, so I'm not interested in selecting all 10.000+ records.

If it's possible, I would like select the first record, the last record and 200 evenly spaced records in-between with a single MySQL-query, so that the result can be passed to my plotting algorithm.

I have seen other similar solutions, where every n'th row starting at (1,2,3.. etc) is selected, like explained here: How to select every nth row in mySQL starting at n

So far I have accomplished to select the first record + 200 evenly spaced records

set @row:=-1; set @numrows := (SELECT COUNT(*) FROM mytable); set @everyNthRow := FLOOR(@numrows / 200); SELECT r.* FROM ( SELECT * FROM mytable ORDER BY ID ASC ) r CROSS JOIN ( SELECT @i := 0 ) s HAVING ( @i := @i + 1) MOD @everyNthRow = 1 

But I can't figure out how to include the last record as well.

How can this be accomplished?

EDIT: Furthermore, I would like to check whether the table is actually containing more than 200 records, before applying the desired logic. If not, the select statement should just output every record (so that the first 200 entries of the datalogging-session will also appear).

3
  • 1
    I guess you can always add UNION and select last row only Commented Oct 21, 2015 at 11:02
  • HAVING @i = @numrows OR ( @i := @i + 1) MOD @everyNthRow = 1 Commented Oct 21, 2015 at 11:04
  • #Veljko89, I already tried that, but when I add the following command: 'UNION SELECT * FROM plotdata ORDER BY id DESC LIMIT 1' to what you see above, I only get the last record? Commented Oct 21, 2015 at 11:07

1 Answer 1

0

Try expanding your HAVING clause to include the last row.

HAVING ( @i := @i + 1) MOD @everyNthRow = 1 OR @i = @numrows 

You may need to experiment as it could be @i = @numrows - 1 that gives the right result.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.