检查最后一次最大值的约束

时间:2016-02-02 15:17:30

标签: postgresql constraints

如何对字段中的最后一个最大值进行检查约束?例如,在以下内容中:

CREATE TABLE prisoner (
    prisoner_id    SERIAL4 PRIMARY KEY,
    name           TEXT NOT NULL CHECK(length(name) <= 256)
);

CREATE TABLE meals (
    prisoner_id       INT4 REFERENCES prisoner,
    last_meal_time    TIMESTAMP(6) WITH TIME ZONE NOT NULL DEFAULT now()        
);

我如何确保last_meal_time总是>=而不是给定last_meal_time的最后一个prisoner_id?换句话说,我将无法追溯给另一名囚犯喂食另一顿饭。

2 个答案:

答案 0 :(得分:2)

您可以在检查约束中使用函数,例如:

create table t(id serial, p int, ts timestamp);

create function t_max_time(p_id int) returns timestamp as $$ select max(ts) from t where p = p_id $$ language sql;

alter table t add constraint t_ts_check check (ts >= t_max_time(p));

-- Thanks to Clodoaldo Neto attention,
-- To prevent changes in other concurrent transactions while our transaction is active we can lock table for exclusive editing like:
lock table t in exclusive mode nowait;
-- It locks table or raises exception if table already locked by another transaction

insert into t(p, ts) values (1, '2016-02-02 10:10:10'), (1, '2016-02-02 11:11:11'); -- It works

insert into t(p, ts) values (1, '2016-02-02 09:09:09'); -- Constraint violation

答案 1 :(得分:0)

设置主键:

insert into meals (prisoner_id) values (1);

请注意,它是clock_timestamp

并始终插入默认值:

string_view