如果其他字段相同,Postgres非唯一,否则是唯一的?

时间:2016-12-06 15:13:43

标签: sql postgresql constraints unique

我希望执行以下操作:

创建一个约束,其中用户可以声明唯一的网址,并且他们可以根据需要使用该网址创建任意数量的行,但其他用户一旦创建了该网址就无法使用该网址。

任何人都知道我是怎么做到的?谢谢!

2 个答案:

答案 0 :(得分:2)

您希望网址对用户来说是唯一的,但之后不是唯一的。

如果您枚举了用户的每个网址,则可以使用过滤/部分索引执行此操作。

create unique index idx_t_user_url_seqnum on t(user, url, seqnum)
    where seqnum = 1;

但是,我认为问题在于您的数据模型。你试图用一张桌子做太多。我认为你应该有一个映射表,其中包含URL和用户之间的映射:

create table UserUrlMapping (
    UserUrlMappingId serial primary key,
    UserId int references Users(UserId),
    Url varchar(4000)
    constraint unq_url unique (Url)  -- If you think about it, being in this table once means that there is only one user
);

然后,在您的数据表中,不要将URL放在那里,而是放置UserUrlMappingId

答案 1 :(得分:1)

首先,创建一个将URL与用户关联的表:

CREATE TABLE url_allocations (
    url     text NOT NULL,
    user_id uuid NOT NULL,
    PRIMARY KEY (url),
    FOREIGN KEY (user_id)
        REFERENCES users(id)
        ON DELETE CASCADE
);

由于主键约束,现在每个URL只能由一个用户使用。接下来,为表创建一个外键:

CREATE TABLE links (
    id      uuid NOT NULL,
    url     text NOT NULL,
    -- ...
    PRIMARY KEY (id),
    FOREIGN KEY (url)
        REFERENCES url_allocations(url)
        ON DELETE RESTRICT
);

现在可以通过加入url_allocations找到链接的用户ID。