首页 > 怎样实现数据库隔行查询?(PostgreSQL)

怎样实现数据库隔行查询?(PostgreSQL)

如题。

例如查询出所有的奇数行,或者按指定的间隔行数查询


select from (select t., row_number() over(partition by a order by b) from t) t1 where num%2=1


用sequence可以勉强达到这个目的

create temp sequence foo;
select * from (select *, nextval('foo') as n from table) as t where t.n % 2 = 0;

如果已经有自增长的字段就不需要用sequence,直接用那个字段来取模就可以了

不过用temporay sequence的好处是必然可以保证值是连续的,而已有的自增长字段不一定可以保证连续

另外就是如果在同一个connect session里面重复利用同一个temporay sequence来做这种计算的话,select之前最好reset sequence一下

【热门文章】
【热门文章】