[英]Unique value Constraint with multiple columns across the table, not the combination in Oracle
In oracle is there a way to enforce uniqueness among two columns?在 oracle 中有没有办法在两列之间强制唯一性?
Its not the uniqueness among combination of two columns, but values across table among two columns.它不是两列组合之间的唯一性,而是两列之间跨表的值。
References:参考:
Unique value constraint across multiple columns 跨多列的唯一值约束
Example data, which should not be allowed:不应允许的示例数据:
id | phone1 | phone2
1 | 111 | 111
id | phone1 | phone2
1 | 111 | NULL
2 | 111 | NULL
id | phone1 | phone2
1 | 111 | NULL
2 | NULL | 111
Unique constraint on combination of two columns? 对两列组合的唯一约束?
My Oracle Version:我的 Oracle 版本:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
I would use a check()
constraint to ensure unicity on each row, and a unique index for unicity across rows:我会使用
check()
约束来确保每一行的唯一性,以及跨行唯一性的唯一索引:
create table mytable (
id int,
phone1 int,
phone2 int,
check (phone1 <> phone2)
);
create unique index myidx on mytable(
greatest(coalesce(phone1, phone2), coalesce(phone2, phone1)),
least(coalesce(phone1, phone2), coalesce(phone2, phone1))
);
The upside of this approach is that it also prevents inserts of tuples like (111, 222)
and (222, 111)
.这种方法的好处是它还可以防止插入像
(111, 222)
和(222, 111)
这样的元组。
Demo on DB Fiddle : DB Fiddle 上的演示:
insert into mytable values(1, 111, 111);
ORA-02290: check constraint (FIDDLE_SMBYKTEIHNNVOHKZSCYK.SYS_C0020876) violated
begin
insert into mytable values(1, 111, null);
insert into mytable values(1, 111, null);
end;
/
ORA-00001: unique constraint (FIDDLE_SMBYKTEIHNNVOHKZSCYK.MYIDX) violated ORA-06512: at line 3
begin
insert into mytable values(1, 111, null);
insert into mytable values(1, null, 111);
end;
/
ORA-00001: unique constraint (FIDDLE_SMBYKTEIHNNVOHKZSCYK.MYIDX) violated ORA-06512: at line 3
begin
insert into mytable values(1, 111, 222);
insert into mytable values(1, 222, 111);
end;
/
ORA-00001: unique constraint (FIDDLE_SMBYKTEIHNNVOHKZSCYK.MYIDX) violated ORA-06512: at line 3
I'd solve it with a combination of a check constraint and a unique index on a function:我会结合检查约束和 function 上的唯一索引来解决它:
CREATE TABLE t(id NUMBER, phone1 NUMBER, phone2 NUMBER);
ALTER TABLE t ADD CONSTRAINT c1 CHECK (phone1 <> phone2);
CREATE UNIQUE INDEX u ON t(COALESCE(phone1, phone2));
Case 1 works:案例1作品:
INSERT INTO t VALUES (1, 111, 111);
ORA-02290: check constraint (C1) violated
Case 2 works, too:案例 2 也有效:
INSERT INTO t VALUES (1, 111, NULL);
INSERT INTO t VALUES (2, 111, NULL);
ORA-00001: unique constraint (U) violated
Case 3, as well:案例3,同样:
INSERT INTO t VALUES (1, 111, NULL);
INSERT INTO t VALUES (2, NULL, 111);
ORA-00001: unique constraint (WFL.U) violated
However, this is not protected:但是,这不受保护:
INSERT INTO t VALUES (1, 111, 222);
INSERT INTO t VALUES (2, 222, 111);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.