我有一个包含三列的表-c_id,o_id,f_id。只要f_id不是3,三个ID的组合就必须唯一。
阅读类似的问题后,我尝试了以下操作:
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));
但是我遇到了缺少表达式错误。我也尝试过
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));
但是对于这个,我得到了无法创建索引;找到重复的键
最初我尝试过
when f_id <> 3 then (c_id, o_id, f_id)
但这根本不起作用。
无论如何,索引可能出问题了,因为该表似乎没有任何重复项,我没有获得任何记录
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;
我对这些FBI视而不见,因此将不胜感激。
答案 0 :(得分:1)
您似乎想要一个三部分索引:
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
);
答案 1 :(得分:1)
仅具有一个列索引的替代方法:
create unique index all_but_3 on tst (case when nvl(f_id,0) != 3 then o_id||'.'||c_id||'.'||f_id end);
测试
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