executable
executable

Reputation: 3600

How to select n row from table where there is 300'000 rows

I'm trying to take every 4 rows from my table, but I have some error with my query.

Here is my table :

id | IfInOctets |  IfOutOctets | inDiff | outDiff |    time    | timeDiff
---------------------------------------------------------------------------
1  | 283994207  |  117876089   |  1716  |  52872  | 1555658221 |    59
2  | 283995596  |  117928892   |  1389  |  52803  | 1555658282 |    61
3  | 283995978  |  117929215   |  382   |  323    | 1555658341 |    59
4  | 283996278  |  117929407   |  300   |  192    | 1555658402 |    61
5  | 283996595  |  117929703   |  317   |  296    | 1555658461 |    59
6  | 283998848  |  117932946   |  2253  |  3243   | 1555658522 |    61
7  | 284001482  |  117935214   |  2634  |  2268   | 1555658581 |    59
8  | 284001824  |  117935472   |  342   |  258    | 1555658642 |    61
9  | 284004728  |  117939762   |  2904  |  4290   | 1555658701 |    59

My query is :

SELECT t.id, t.time
FROM
(
    SELECT id, `time`, ROW_NUMBER() OVER (ORDER BY `time`) AS rownum
    FROM monitor
) AS t
WHERE t.rownum % 25 = 0
ORDER BY t.time

The error :

1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(ORDER BY `time`) AS rownum FROM mytable ) AS t WHERE t.rownu' at line 4

You can try here :

http://www.sqlfiddle.com/#!9/8074b4/3

Upvotes: 0

Views: 239

Answers (2)

Ravi Sharma
Ravi Sharma

Reputation: 370

select * from table where id in (select id from table where id%4=0)

Upvotes: 1

Nick
Nick

Reputation: 147166

You can emulate the ROW_NUMBER() function using variables in MySQL prior to 8.0:

SELECT t.id, t.time
FROM (SELECT id, time, @rownum := @rownum + 1 AS rownum
      FROM monitor
      CROSS JOIN (SELECT @rownum := 0) r
      ORDER BY time) t
WHERE t.rownum % 4 = 0
ORDER BY t.time

Output (for your sample data):

id  time
4   1555658402
8   1555658642

Demo on dbfiddle

Upvotes: 2

Related Questions