CREATE TABLE foo ( dt AS DATE, ts AS TIMESTAMP );
什么是创建一个唯一约束的正确方法,其中的日期值ts每秒发生一次dt; 例子:
ts
dt
dt | ts 2010-01-02 | 2010-01-02 17:19:08 2010-01-02 | 2011-11-11 01:01:01 2010-01-02 | 2011-11-11 17:19:08 -- would error on insert (already a 2011-11-11)
试图:
语法无效,但是我要达到的目的是:
CREATE UNIQUE INDEX unique_tsdate_per_dt ON foo(dt,ts::date);
尝试未完成-可能是子查询?
CREATE UNIQUE INDEX unique_tsdate_per_dt ON foo(dt) WHERE ts::date -- ?
我认为您正在寻找::date演员表的功能形式:
::date
CREATE UNIQUE INDEX unique_tsdate_per_dt ON foo(dt, date(ts));
然后,您将获得如下结果:
=> insert into foo (dt, ts) values ('2010-01-02', '2010-01-02 17:19:08'); => insert into foo (dt, ts) values ('2010-01-02', '2011-11-11 01:01:01'); => insert into foo (dt, ts) values ('2010-01-02', '2011-11-11 17:19:08'); ERROR: duplicate key value violates unique constraint "unique_tsdate_per_dt" DETAIL: Key (dt, date(ts))=(2010-01-02, 2011-11-11) already exists.