[英]Can I make a unique constraint in Oracle on a combination of 2 columns from 2 different tables?
Column A is the PK of table A. Column B is a column in table B. Column C is a FK is table B that references column A in table A. A 列是表 A 的 PK。B 列是表 B 中的列。C 列是 FK 是表 B,它引用表 A 中的列 A。
Can I define a constraint that says that that a column B AND column C have to be unique?我可以定义一个约束,说明 B 列和 C 列必须是唯一的吗? As in, I don't want any repeats of the same combination of values from A and B.
如在,我不希望 A 和 B 的相同值组合的任何重复。
Here's one possibility i'm thinking about:这是我正在考虑的一种可能性:
unique_id varchar2 GENERATED ALWAYS AS (B || '-' || FK that references column A) VIRTUAL
CONSTRAINT unique_id UNIQUE
If i go with this solution i'm confused about one thing.如果我用这个解决方案 go 我对一件事感到困惑。 The docs say: "Virtual columns are not supported for index-organized, external, object, cluster, or temporary tables."
文档说:“索引组织的、外部的、object、集群或临时表不支持虚拟列。” Obviously, because they don't get stored like other columns.
显然,因为它们不像其他列那样被存储。 Would this be a problem if I wanted to make my tables clustered?
如果我想让我的表聚集在一起,这会是一个问题吗?
Yes, you can create a UNIQUE
constraint on two columns.是的,您可以在两列上创建
UNIQUE
约束。 For example:例如:
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)
);
Then, if you try to insert it will fail for duplicates.然后,如果您尝试插入它将因重复而失败。 For example:
例如:
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);
See running example at db<>fiddle .请参阅db<>fiddle的运行示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.