我可以在 Oracle 中对来自 2 个不同表的 2 列的组合进行唯一约束吗?
Can I make a unique constraint in Oracle on a combination of 2 columns from 2 different tables?
A 列是 table A 的 PK。B 列是 table B 中的列。C 列是 FK 是 table B,它引用了 [=] 中的 A 列36=] A.
我可以定义一个约束条件,规定 B 列和 C 列必须是唯一的吗?比如,我不想重复 A 和 B 的相同值组合。
这是我正在考虑的一种可能性:
- 创建唯一 ID 列。
unique_id varchar2 GENERATED ALWAYS AS (B || '-' || FK that references column A) VIRTUAL
- 设置为唯一
CONSTRAINT unique_id UNIQUE
如果我采用此解决方案,我会对一件事感到困惑。文档说:“索引组织的、外部的、对象的、集群的或临时的 table 不支持虚拟列。”显然,因为它们不像其他列那样存储。如果我想让我的 table 成簇,这会有问题吗?
是的,您可以在两列上创建 UNIQUE
约束。例如:
create table table_a (
a number(6) primary key not null
);
create table table_b (
b number(6) not null,
c number(6) not null,
constraint uq1 unique (b, c),
constraint fk1 foreign key (c) references table_a (a)
);
然后,如果您尝试插入,它将因重复而失败。例如:
insert into table_a (a) values (1);
insert into table_a (a) values (2);
insert into table_b (b, c) values (10, 1);
insert into table_b (b, c) values (10, 1); -- fails!
insert into table_b (b, c) values (10, 2);
参见 db<>fiddle 中的 运行 示例。
A 列是 table A 的 PK。B 列是 table B 中的列。C 列是 FK 是 table B,它引用了 [=] 中的 A 列36=] A.
我可以定义一个约束条件,规定 B 列和 C 列必须是唯一的吗?比如,我不想重复 A 和 B 的相同值组合。
这是我正在考虑的一种可能性:
- 创建唯一 ID 列。
unique_id varchar2 GENERATED ALWAYS AS (B || '-' || FK that references column A) VIRTUAL
- 设置为唯一
CONSTRAINT unique_id UNIQUE
如果我采用此解决方案,我会对一件事感到困惑。文档说:“索引组织的、外部的、对象的、集群的或临时的 table 不支持虚拟列。”显然,因为它们不像其他列那样存储。如果我想让我的 table 成簇,这会有问题吗?
是的,您可以在两列上创建 UNIQUE
约束。例如:
create table table_a (
a number(6) primary key not null
);
create table table_b (
b number(6) not null,
c number(6) not null,
constraint uq1 unique (b, c),
constraint fk1 foreign key (c) references table_a (a)
);
然后,如果您尝试插入,它将因重复而失败。例如:
insert into table_a (a) values (1);
insert into table_a (a) values (2);
insert into table_b (b, c) values (10, 1);
insert into table_b (b, c) values (10, 1); -- fails!
insert into table_b (b, c) values (10, 2);
参见 db<>fiddle 中的 运行 示例。