Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 如何从postgres表中获取下一个唯一行_Postgresql - Fatal编程技术网

Postgresql 如何从postgres表中获取下一个唯一行

Postgresql 如何从postgres表中获取下一个唯一行,postgresql,Postgresql,假设我的表包含两列“id”(类型为字符变化(22))和“time”(类型为不带时区的时间戳) 现在我在表中有一些数据如下: id time P001 2015-02-04 10:00:00 P002 2015-02-04 10:00:00 P003 2015-02-04 10:00:00 P004 2015-02-04 10:10:00 P005 2015-02-04 11:00:00 获取第一行的查询将是: select * from &

假设我的表包含两列“id”(类型为字符变化(22))和“time”(类型为不带时区的时间戳)

现在我在表中有一些数据如下:

id        time
P001     2015-02-04 10:00:00
P002     2015-02-04 10:00:00
P003     2015-02-04 10:00:00
P004     2015-02-04 10:10:00
P005     2015-02-04 11:00:00
获取第一行的查询将是:

select * from <tablename> order by time, id limit 1;
按时间从订单中选择*,id限制1;

在此之后,查询下一行的id值为“P002”

一般来说,您可以使用offset进行查询,但是如果
时间上有索引,id
则可以稍微提高数据库的效率(只有在有数百万行的情况下才可以真正注意到)

标准溶液:

select * from <tablename>
order by time, id limit 1 offset 1;
select * from <tablename>
where time >= '2015-02-04 10:00:00' and id > 'P001'
order by time, id limit 1;
从中选择*
按时间排序,id限制1偏移量1;
索引(通常更快)解决方案:

select * from <tablename>
order by time, id limit 1 offset 1;
select * from <tablename>
where time >= '2015-02-04 10:00:00' and id > 'P001'
order by time, id limit 1;
从中选择*
其中时间>='2015-02-04 10:00:00'和id>'P001'
按时间顺序,id限制为1;

偏移量
:感谢您的快速回复。但我不能在这里使用偏移量,原因有二:第一,我们可以按时间的相反顺序显示数据,第二,数据正在随机添加到表中。您能否在不使用偏移量的情况下关闭查询?如果您可以正确排序数据(这是正确使用
限制所必需的)然后当然可以使用
offset