如何从有30万行的表中选择n行

时间:2019-04-19 07:41:44

标签: mysql sql

我正在尝试从表中每隔4行进行查询,但是查询中出现了一些错误。

这是我的桌子:

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

我的查询是:

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

错误:

  

1064您的SQL语法有错误;检查手册   对应于您的MariaDB服务器版本,以使用正确的语法   在'(ORDER BY`time`)AS rownum附近           来自mytable       )       在第4行的t.rownu'

您可以在这里尝试:

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

2 个答案:

答案 0 :(得分:2)

您可以在8.0之前的MySQL中使用变量来模拟ROW_NUMBER()函数:

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

输出(用于您的示例数据):

id  time
4   1555658402
8   1555658642

Demo on dbfiddle

答案 1 :(得分:1)

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