sql - 如何为Oracle中的列和固定值的组合赋予唯一约束?

标签 sql oracle constraints unique-constraint composite-key

我有一个包含 3 列的表:A(数字)、B(数字)和 C( bool 值)。

我需要创建一个规则,以防止使用列 A 和 B 以及 C 等于 true 创建记录。例如。

这是允许的:

A  B  C
1  2  true
1  2  false
1  2  false

但是这个,不:

A  B  C
1  2  true
1  2  true
1  2  false

最佳答案

MarmiteBomber 的方法略有不同,以避免连接值(这可能导致与非整数值发生意外冲突):

create table t (a number, b number, c varchar2(5),
  constraint t_chk check (c in ('true', 'false'))
);

create unique index t_unq
on t (case when c = 'true' then a end, case when c = 'true' then b end);

insert into t(a,b,c) values (1,2,'true');

1 row inserted.

insert into t(a,b,c) values (1,2,'false');

1 row inserted.

insert into t(a,b,c) values (1,2,'false');

1 row inserted.

insert into t(a,b,c) values (1,2,'true');

ORA-00001: unique constraint (MY_SCHEMA.T_UNQ) violated

select * from t;

         A          B C    
---------- ---------- -----
         1          2 true 
         1          2 false
         1          2 false

为什么非整数(如果它们可以存在)可能是一个问题的快速示例:

create unique index uq_true on test(case when c = 'true' then a||'.'||b end);

insert into test(a,b,c) values (1.1, 2,'true');

1 row inserted.

insert into test(a,b,c) values (1, 1.2,'true');

ORA-00001: unique constraint (MY_SCHEMA.UQ_TRUE) violated

select * from test;

         A          B C    
---------- ---------- -----
       1.1          2 true 

... 因为对于两个 '1.1' ||'.'|| '2''1' ||'.'|| '1.2' 解析为相同的字符串,'1.1.2'

当组合字符串值而不是数字时,这也可能是一个问题。在任何一种情况下,您都可以通过使用任何一个值中都不存在的分隔符来避免它;字符串更难处理,但对于数字,除了句点(或逗号是安全的)之外的任何标点符号都可能会这样做 - 除非有人对 nls_numeric_characters...

有一个奇怪的设置

关于sql - 如何为Oracle中的列和固定值的组合赋予唯一约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57222741/

相关文章:

sql - 数据库表设计-邮件类型的不同状态

java - Drools 硬约束实现

c# - 有约束为约束

php - 这5张表的SQL查询怎么写?

sql - 查询性能: single column vs multiple column

mysql - 有条件触发

windows - 如何在Windows命令脚本中使用sql*plus进行流控?

oracle - TNS : No listener from other user

mysql - Select from Different Tables Where 两个子句

c# - Entity-Framework中自动查询结果