PostgreSQL 如何查找最近 n 分钟内的任何更改

2024-02-29

我正在编写一个同步 PostgreSQL 和 MS SQL 服务器数据库的程序(并在此转换中添加一些更改)。对于数百万条记录,需要很长时间,并且服务器负载非常糟糕select *;它还需要更多资源来解析未更改的记录并根据 MS SQL 服务器验证它们。

PostgreSQL 中是否有任何日志可供我解析以找出最近 n 分钟内发生的更改?这将允许我只选择那些我需要工作的记录;提高性能。


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 │ 
    └────────────────────┴──────────────┴────────────────────────────┘ 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PostgreSQL 如何查找最近 n 分钟内的任何更改 的相关文章

随机推荐