English 中文(简体)
PostgreSQL: 如何获取上一个插入时间戳
原标题:PostgreSQL: how to fetch previous insert timestamp

假设我有桌子

create table foo (
    insert_current timestamp default now(),
    insert_previous timestamp,
    bar int primary key,
    baz varchar(10)
);

数据将在新批次到达时立即替换。 我想继续跟踪前批次何时插入以及当前时间戳。 这样做的好办法是什么?

最佳回答

我会设定一个触发器,自动设置插入_当前并在更新的语句中插入_前插入_。

首先,创造触发功能:

CREATE OR REPLACE FUNCTION do_update() RETURNS "trigger"
AS $$
BEGIN
    NEW.insert_previous := OLD.insert_current;
    NEW.insert_current := NOW();
    return NEW;
END;
$$
LANGUAGE plpgsql;

然后把触发器加到桌子上

CREATE TRIGGER do_update
BEFORE UPDATE ON foo
FOR EACH ROW
EXECUTE PROCEDURE do_update();
问题回答

当您更新一行时, 将 < code> 插入当前 < / code > 的值复制到 < code> 插入前 < / code >, 并将 < code> 插入当前 < / code > 设置为当前时间戳 :

UPDATE foo
   SET baz =  whatever ,
       insert_previous = insert_current,
       insert_current  = NOW()
 WHERE bar = 1;




相关问题
摘录数据

我如何将Excel板的数据输入我的Django应用? I m将PosgreSQL数据库作为数据库。

Postgres dump of only parts of tables for a dev snapshot

On production our database is a few hundred gigabytes in size. For development and testing, we need to create snapshots of this database that are functionally equivalent, but which are only 10 or 20 ...

How to join attributes in sql select statement?

I want to join few attributes in select statement as one for example select id, (name + + surname + + age) as info from users this doesn t work, how to do it? I m using postgreSQL.

What text encoding to use?

I need to setup my PostgreSQL DB s text encoding to handle non-American English characters that you d find showing up in languages such as German, Spanish, and French. What character encoding should ...

SQL LIKE condition to check for integer?

I am using a set of SQL LIKE conditions to go through the alphabet and list all items beginning with the appropriate letter, e.g. to get all books where the title starts with the letter "A": SELECT * ...

热门标签