简体   繁体   English

oracle中多列的条件唯一约束

[英]conditional unique constraint on multiple columns in oracle

I have a table with three columns - c_id, o_id, f_id. 我有一个包含三列的表格-c_id,o_id,f_id。 The combination of the three ids has to be unique as long as f_id is not 3. 只要f_id不为3,则三个ID的组合必须唯一。

After reading similar questions I tried the following : 阅读类似的问题后,我尝试了以下操作:

create unique index my_index on my_table (
decode (f_id, !3, c_id, null),
decode (f_id, !3, o_id, null),
decode (f_id, !3, f_id, null));

but I'm getting a missing expression error. 但我遇到了一个表达失误的错误。 I also tried with 我也尝试过

create unique index my_index on my_table ((
case 
when f_id <> 3 then c_id
when f_id <> 3 then o_id
when f_id <> 3 then f_id
else null
end));

but for this one I'm getting cannot create index; 但是对于这个我无法创建索引; duplicate keys found 找到重复的密钥

Originally I tried 本来我试过

when f_id <> 3 then (c_id, o_id, f_id)

but that didn't work at all. 但这根本没有用。

Anyhow, something is probably wrong with the index as the table doesn't seem to have any duplicates, I get no records with 无论如何,索引可能出了问题,因为该表似乎没有任何重复项,因此我没有记录

select c_id, o_id, f_id, count(*) as dupes
from my_table
where f_id <> 3
having count(*) > 1
group by c_id, o_id, f_id;

I'm kinda running blind with these FBIs, so any help would be appreciated. 我对这些FBI视而不见,因此将不胜感激。

You seem to want a 3-part index: 您似乎想要一个三部分索引:

create unique index my_index
    on my_table (case when f_id <> 3 then c_id end,
                 case when f_id <> 3 then o_id end,
                 case when f_id <> 3 then f_id end
                );

Alternative approach with only one column index: 仅具有一个列索引的替代方法:

create unique index all_but_3 on tst (case when nvl(f_id,0) != 3 then o_id||'.'||c_id||'.'||f_id end);

Test 测试

insert into tst(c_id, o_id, f_id) values(3,3,3);
insert into tst(c_id, o_id, f_id) values(3,3,3); -- OK

insert into tst(c_id, o_id, f_id) values(3,3,2);
insert into tst(c_id, o_id, f_id) values(3,3,2); -- ORA-00001: unique constraint  xxx violated

insert into tst(c_id, o_id, f_id) values(3,3,null);
insert into tst(c_id, o_id, f_id) values(3,3,null); -- ORA-00001: unique constraint  xxx violated

insert into tst(c_id, o_id, f_id) values(null,null,2);
insert into tst(c_id, o_id, f_id) values(null,null,2); -- -- ORA-00001: unique constraint  xxx violated

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM