Postgresql,查找最近n分钟的变化:
Postgresql 不会自动存储添加/更新/删除行的日期或时间(如果您不希望这样做,处理这样的时间戳确实会减慢速度)。
您必须自己执行此操作:将时间戳列添加到表中。当您向表中插入一行时,让它将时间戳列更新为current_timestamp
。当您选择行时,请使用 select 语句来过滤时间戳大于 N 分钟前的位置,如下所示:
获取时间戳大于日期的行:
SELECT * from yourtable
WHERE your_timestamp_field > to_date('05 Dec 2000', 'DD Mon YYYY');
获取最近 n 分钟内已更改的行:
SELECT * from yourtable
WHERE your_timestamp_field > current_timestamp - interval '5 minutes'
演练示例
drop table foo;
CREATE TABLE foo(
msg character varying(20),
created_date date,
edited_date timestamp
);
insert into foo values( 'splog adfarm coins', '2015-01-01', current_timestamp);
insert into foo values( 'execute order 2/3', '2020-03-15', current_timestamp);
insert into foo values( 'deploy wessels', '2038-03-15', current_timestamp);
select * from foo where created_date < to_date('2020-05-05', 'YYYY-mm-DD');
┌────────────────────┬──────────────┬────────────────────────────┐
│ msg │ created_date │ edited_date │
├────────────────────┼──────────────┼────────────────────────────┤
│ splog adfarm coins │ 2015-01-01 │ 2020-12-29 11:46:27.968162 │
│ execute order 2/3 │ 2020-03-15 │ 2020-12-29 11:46:27.96918 │
└────────────────────┴──────────────┴────────────────────────────┘
select * from foo where edited_date > to_timestamp(
'2020-12-29 11:42:37.719412', 'YYYY-MM-DD HH24_MI_SS.US');
┌────────────────────┬──────────────┬────────────────────────────┐
│ msg │ created_date │ edited_date │
├────────────────────┼──────────────┼────────────────────────────┤
│ execute order 2/3 │ 2020-03-15 │ 2020-12-29 11:46:27.96918 │
│ deploy wessels │ 2038-03-15 │ 2020-12-29 11:46:27.969988 │
└────────────────────┴──────────────┴────────────────────────────┘