PostgreSQL如何设置带有时间戳的主键列自动填充

PostgreSQL how to set a Primary Key column with timestamp to automatically be filled

我怎样才能在 PostgreSQL 中实现这个?

我想要一个带有时间戳字段的 table,该字段在插入时自动获取 now() 的值。时间戳永远不会更新。我假设我需要创建一个触发器来执行此操作。如果有更简单的方法,请指教

也许,创建该列使其具有默认值 now,登陆然后插入而不指定时间戳列以使其获得默认值?

创建table foo (q_i_time timestamp with time zone not null default now(), someval int);

CREATE TABLE
billing=# insert into foo (someval) values (22);
INSERT 0 1
billing=# insert into foo (someval) values (26);
INSERT 0 1
billing=# insert into foo (someval) values (1);
INSERT 0 1
billing=# select * from foo;

           q_i_time            | someval
-------------------------------+---------
 2008-02-25 17:23:03.247619-08 |      22
 2008-02-25 17:23:07.43922-08  |      26
 2008-02-25 17:23:10.111189-08 |       1
(3 rows)

这个自动填充的时间戳列可以作为主键吗?

感谢高级。

不需要触发器,因为您没有更新时间戳。只需声明一个 DEFAULT,例如

CREATE TABLE demo (
    id integer primary key,
    created_at timestamp not null default current_timestamp
);

示例:

test=>     CREATE TABLE demo (
test(>         id integer primary key,
test(>         created_at timestamp not null default current_timestamp
test(>     );
CREATE TABLE
test=> INSERT INTO demo(id) VALUES(1),(2);
INSERT 0 2
test=> INSERT INTO demo(id) VALUES(3);
INSERT 0 1
test=> SELECT * FROM demo;
 id |         created_at         
----+----------------------------
  1 | 2015-06-13 12:30:55.169221
  2 | 2015-06-13 12:30:55.169221
  3 | 2015-06-13 12:30:57.395104
(3 rows)

请注意,前两个时间戳是相同的,因为它是单个事务。如果您不希望这样,请使用 clock_timestamp 而不是 current_timestamp

请注意,应用程序仍然可以通过明确指定来覆盖时间戳:

test=> INSERT INTO demo(id, created_at) VALUES (4, '2014-01-01 00:00:00');
INSERT 0 1
test=> SELECT * FROM demo WHERE id = 4;
 id |     created_at      
----+---------------------
  4 | 2014-01-01 00:00:00
(1 row)

如果您希望强制该值,或者如果您还想更新该行时,您只需要一个触发器已更新。