![](/img/trans.png)
[英]How can I write a SQL query which ensures two columns are independently unique?
[英]How can I make a unique constraint order independently on two columns
我正在使用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)约束是不够的。 您有什么建议吗?
您可以创建基于函数的索引
CREATE UNIQUE INDEX idx_unique_edge
ON map( greatest( point_one, point_two ),
least( point_one, point_two ) );
我假设point_one
和point_two
的数据类型与Oracle greatest
和least
函数兼容。 如果不是这样,您将需要自己的函数来为复杂数据类型选择“最大”和“最小”点。
您可以使用触发器轻松实现所需的结果。
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);
已创建1行。
SQL>插入映射值(2,1,10); 插入地图值(2,1,10)*第1行出现错误:ORA-21000:raise_application_error为-100的错误号参数超出范围ORA-06512:在“ C ## MINA.TR_MAP”的第10行ORA- 04088:执行触发器“ C ## MINA.TR_MAP”时出错
我仍在考虑CHECK约束,但是我并没有决定是否可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.