我正在根据本文的架构设计一个带有审计跟踪的表:
https://www.codeproject.com/Articles/105768/Audit-Trail-Tracing-Data-Changes-in-Database
其要点是,当您更新一行时,您只需插入当前行的副本,然后更新该行,以便您获得数据在某个时间点的状态历史记录。以下是文章中表格外观的示例:
我的问题是关于第一个插入的。插入第一行时,我需要将original_id标记为与该行的id相同。我可以在一份声明中做到这一点吗?或者我是否必须先插入新行,然后使用新 id 更新original_id 列。
根据示例图片,插入语句如下所示:
begin;
insert into people (status, name, created_date, created_by)
values ('active', 'Julia Singleton', 'today', 'me')
returning id;
// use the returned id to update original_id on the row
// ...
commit;
我很好奇这是否可以在 1 个语句中完成。
使用 OP 显示的示例,您可以将
default
列的 original_id
值指定为负责生成 id
的序列的当前值 - 如果将其设置为 serial
或 identity column
,您可以通过 pg_get_serial_sequence()
: 动态获取它
create table people (
id bigint generated by default as identity primary key, --bigserial primary key
original_id bigint not null default currval(pg_get_serial_sequence('"people"', 'id')),
status text,
name text,
created_date date,
created_by text);