oracle 如何基于两列值在表上创建唯一约束

ldioqlga  于 2022-11-22  发布在  Oracle
关注(0)|答案(1)|浏览(198)
Select
      1 as TYPE_ID,
      0 as STATUS
from
     dual  --TEST_TBL
union all
Select
      1 as TYPE_ID,
      0 as STATUS
from
     dual --TEST_TBL
     union all
Select
      1 as TYPE_ID,
      1 as STATUS
from
     dual  --TEST_TBL

状态= 1表示活动,0表示非活动
不允许两行类型标识= 1且状态= 1或类型标识= 2且状态= 1

klr1opcd

klr1opcd1#

可以使用基于函数的唯一索引:

create unique index test_table_ix
on test_table (case when status = 1 then type_id end)

索引中只包含非空值,因此case表达式在状态0时计算为空值(表示这些行没有索引),在状态1时计算为type_id(表示这些行有索引)。这意味着1,0没有索引,但1,1有索引,因此必须是唯一的。
fiddle

相关问题