2
CREATE TABLE foo (
    dt AS DATE,
    ts AS TIMESTAMP
);

什么是创建唯一约束的正确方法,其中的日期值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)

试图:

  1. 无效的语法,但我想要实现的目标:

    CREATE UNIQUE INDEX unique_tsdate_per_dt ON foo(dt,ts::date);
    
  2. 不完整的尝试 - 可能是子查询?

    CREATE UNIQUE INDEX unique_tsdate_per_dt ON foo(dt) WHERE ts::date -- ?
    
4

1 回答 1

1

我认为您正在寻找::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.
于 2013-04-08T21:49:57.780 回答