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

标签 postgresql logging changelog

我正在编写一个同步 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 │ 
    └────────────────────┴──────────────┴────────────────────────────┘ 

关于PostgreSQL 如何查找最近 n 分钟内的任何更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13768274/

相关文章:

postgresql - 如何将值从更改的行发送到 postgres 中的触发器?

java - 如何启用日志返回日志堆栈跟踪和未捕获的异常

svn - 格式化 svn 日志输出

javascript - 在 findAll 中续写计数关联

postgresql - 从 Postgresql 函数返回自定义类型

sql - postgres大表选择优化

windows - 实时记录

php - XAMPP tmp 文件夹过大

database-design - 将 Liquibase 与 Snowflake 结合使用

mysql - 具有精度的 liquibase double 型