2017-08-10 78 views
0

我有如下表唯一约束到特定的文本

create table order(
status text, 
user_id int (FK to user table), 
time time stamp with time zone 

); 

而下面的约束的状态

CONSTRAINT valid_status CHECK (status = ANY (ARRAY['requested'::text, 'accepted'::text, 'declined_by_manager'::text, 'declined_by_user'::text, 'finished_by_user'::text, 'canceled_by_system'::text, 'washing'::text, 'finished_by_manager'::text])) 

我想要的是,有可能只有一个订单状态为“要求”并与用户的“n” 水木清华像Alter table order add constraint "only_one_order_per_user" UNIQUE(user_id, status = 'requested') 我真的newbee与Postgres的。在此先感谢

回答

1
create unique index some_name on "order" (user_id, (case when status = 'requested' then 1 else null end)); 

与空<背后的想法>空

也或许你更好的使用ENUM的状态?..甚至更好地创造具有鲜明行和FK的关系状态?..

样品:

t=# create table "order" (
status text, 
user_id int, 
time timestamp with time zone 
); 
CREATE TABLE 
Time: 6.345 ms 
t=# create unique index some_name on "order" (user_id, (case when status = 'requested' then 1 else null end)); 
CREATE INDEX 
Time: 16.979 ms 
t=# insert into "order" select 'requested',1,now(); 
INSERT 0 1 
Time: 17.793 ms 
t=# insert into "order" select 'other',1,now(); 
INSERT 0 1 
Time: 1.137 ms 
t=# insert into "order" select 'other',1,now(); 
INSERT 0 1 
Time: 6.735 ms 
t=# insert into "order" select 'other',1,now(); 
INSERT 0 1 
Time: 0.867 ms 
t=# insert into "order" select 'requested',1,now(); 
ERROR: duplicate key value violates unique constraint "some_name" 
DETAIL: Key (user_id, (
CASE 
    WHEN status = 'requested'::text THEN 1 
    ELSE NULL::integer 
END))=(1, 1) already exists. 
Time: 0.342 ms 
0

试试这个。你应该能够建立你的表,所以你只能有请求的状态,不知道是否允许NULL。然后为user_id和状态添加一个唯一的。

create table order(
status text CHECK (status in ('requested'[add more statuses here])) , 
user_id int, 
time time stamp with time zone 
UNIQUE (status, user_id) 
); 
+0

感谢响应,但状态不仅是请求可以完成,接受和开始,CONSTRAINT valid_status CHECK(status = ANY(ARRAY ['requested':: text,'accepted':: text,'declined_by_manager':: text,'declined_by_user':: text'' finished_by_user'::文本,‘canceled_by_system’::文本,‘洗’::文本,‘finished_by_manager’::文)) –

+0

编辑我的回答对多个状态 – Mokadillion

+0

你的情况,我将无法创建2个declined_by_user订单。我只需要一个状态为“请求”的订单,而第i个用户标识为1 –