如何在两列上独立创建唯一约束顺序

时间:2015-03-13 19:36:42

标签: sql oracle unique-constraint

我正在使用Oracle数据库,我需要创建一个如下所示的表。

MAP(Point_One, Poin_Two, Connection_weight).

该表格表示有关图表的数据。我想创建一个带有约束的表,以防止插入已存在的连接。

例如,该表已包含此连接:

Point_One | Point_Two | Connection_weight
-----------------------------------------
p_no1     | p_no2     | 10

即使我尝试以不同的顺序添加点,约束也会阻止重复插入此连接。 (例如:(p_no2,p_no1,10))

简单的UNIQUE(Point_One,Point_Two)约束是不幸的。你有什么建议吗?

2 个答案:

答案 0 :(得分:6)

您可以创建基于函数的索引

CREATE UNIQUE INDEX idx_unique_edge
    ON map( greatest( point_one, point_two ),
            least( point_one, point_two ) );

我假设point_onepoint_two的数据类型与Oracle greatestleast函数兼容。如果没有,你需要自己的功能,选择最好的"和#34;至少"指出您的复杂数据类型。

答案 1 :(得分:0)

使用触发器可以轻松获得所需的结果。

 create table map (point_one number, point_two number, connection_weight number)
/
 create or replace trigger tr_map before insert on map
 for each row
 declare
 c number;
   begin
     select count(1) into c from map where (point_one=:new.point_one and   point_two=:new.point_two)
     or
     (point_one=:new.point_two and point_two=:new.point_one);
     if c>0 then
     raise_application_error(-20000,'Connection line already exists');
  end if;
end;
  /

SQL>插入地图值(1,2,10);

创建了一行。

SQL>插入地图值(2,1,10); 插入地图值(2,1,10)             * 第1行的错误: ORA-21000:raise_application_error的错误编号参数为-100 范围 ORA-06512:at" C ## MINA.TR_MAP",第10行 ORA-04088:执行触发器时发生错误' C ## MINA.TR_MAP'

我仍然在考虑CHECK约束,但是我是否有可能会判断是否可能。

相关问题