跳过 PostgreSQL 中的每第 n 个结果行 [英] Skip every nth result row in PostgreSQL

查看:74
本文介绍了跳过 PostgreSQL 中的每第 n 个结果行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在 PostgreSQL 中跳过行的方法.

I'm looking for a way to skip rows in PostgreSQL.

我可以使用以下两种方法:

Two ways I could do this are using:

SELECT * FROM table WHERE id % 5 = 0

但是我必须获取连续的行才能正确跳过.例如,如果我获取行(带有 ID)0,3,5,它不会跳过 5 行中的 4 行,而是导致 (ids) 0 和 5.

However I'd have to fetch sequential rows to properly skip. For instance if I fetch row (with ids) 0,3,5, it would not skip 4 out of 5 rows, but instead result in (ids) 0 and 5.

或者在 SQL 之外跳过:

Or skip outside of SQL:

$count = 0;
while($row = progres_fetch_row($result))
  if ($count++ % 5 == 0)
     // do something 

从 SQL 数据库中获取每第 n 行的最快方法是什么?

What is the fastest way to get every nth row from a SQL database?

推荐答案

如果你使用 PostgreSQL,你可以使用 row_number():

If you use PostgreSQL, you can use row_number():

SELECT t.*
FROM (
  SELECT *, row_number() OVER(ORDER BY id ASC) AS row
  FROM yourtable
) t
WHERE t.row % 5 = 0

这篇关于跳过 PostgreSQL 中的每第 n 个结果行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆