删除唯一约束 - PostgreSQL

Dropping Unique Constraint - PostgreSQL

TL;DR

我想澄清一下:FOREIGN KEY 是否需要另一侧的 UNIQUE CONSTRAINT,特别是在 Postgres 中,通常在关系数据库系统中?

也许,我可以对此进行测试,但我会问,如果 FOREIGN KEY 需要 UNIQUE CONSTRAINT,如果我不创建它会怎样?数据库会创建一个还是会抛出错误?

我是怎么到那里的

我早些时候创建了一个 table,其中有一列 username,我对其施加了唯一约束。然后我创建了另一个 table,其列 bearer_name 有一个 FOREIGN KEY 引用前一个 table 的列 username;那个有 UNIQUE CONSTRAINT.

现在,我想从数据库中删除 username 列上的 UNIQUE CONSTRAINT,因为我稍后在同一列上创建了一个 UNIQUE INDEX,直觉上我觉得它们服务于相同的目的,或者不是吗?但是数据库抱怨 UNIQUE INDEX 有一些依赖对象,所以它不能被删除,除非我提供 CASCADE 作为一个选项来删除依赖对象。它将第二个 table 中 bearer_name 列上的 FOREIGN KEY 标识为从属对象。

FOREIGN KEY 是否可以指向 UNIQUE INDEX 而不是 UNIQUE CONSTRAINT

I am seeking clarity on this: does a FOREIGN KEY require a UNIQUE CONSTRAINT on the other side

不,它不需要只 UNIQUE CONSTRAINT。可以是 PRIMARY KEYUNIQUE INDEX.

Perhaps, I can test this, but I'll ask, if the UNIQUE CONSTRAINT is required by the FOREIGN KEY what would happen if I don't create it? Will the Database create one or will it throw an error?

CREATE TABLE tab_a(a_id INT, b_id INT);
CREATE TABLE tab_b(b_id INT);

ALTER TABLE tab_a ADD CONSTRAINT fk_tab_a_tab_b FOREIGN KEY (b_id)  
             REFERENCES tab_b(b_id);
ERROR:  there is no unique constraint matching given keys 
        for referenced table "tab_b"

DBFiddle Demo

And is it possible for the FOREIGN KEY to be a point to the UNIQUE INDEX instead of the UNIQUE CONSTRAINT?

是的,有可能。

CREATE UNIQUE INDEX tab_b_i ON tab_b(b_id);

DBFiddle Demo2