我在数据库中有一个表,其中包含三个字段:id
、value
和 timestamp
。
给定两个日期,我知道如何在 postgres 中编写一个查询,使用 timestamp
字段,将找到一个范围内的所有记录。麻烦的是,我还想找到范围之前最近的单个记录,以及范围之后最近的单个记录。
所以,如果我有这张表:
id | value | timestamp
---+-------+---------------------
1 | 18| Jan, 1 2017, 09:00:000
2 | 16| Jan, 1 2017, 09:05:000
3 | 14| Jan, 1 2017, 09:21:150
4 | 12| Jan, 1 2017, 10:01:150
5 | 13| Jan, 1 2017, 10:07:000
6 | 09| Jan, 1 2017, 10:23:000
我想写一个包含时间的查询:
2017 年 1 月 1 日,9:10:000
到 2017 年 1 月 1 日,10:05:000
并将返回:
id | value | timestamp
---+-------+---------------------
2 | 16| Jan, 1 2017, 09:05:000
3 | 14| Jan, 1 2017, 09:21:150
4 | 12| Jan, 1 2017, 10:01:150
5 | 13| Jan, 1 2017, 10:07:000
id 2
,是最接近范围底部的记录,但仍然小于范围底部。 id 5
,是最接近范围顶部但仍大于(或等于)范围顶部的记录。
最佳答案
使用三个联合:
select * from table where timestamp between start_ts and end_ts
union all
(select * from table where timestamp < start_ts order by timestamp desc limit 1)
union all
(select * from table where timestamp > end_ts order by timestamp limit 1)
所有这些子查询都符合 timestamp
列上的索引。
关于postgresql - 在 postgres 中,如何找到一个范围内的记录,然后在两侧找到范围外的单个记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45723337/