如果可能,请考虑重新建模。创建一个新表。使用旧表的键列,并应用 PK 约束(这将强制唯一性和 NOT NULL)。为您正在处理的每种(子)类型(L,R)设置一列。使用仅允许表示(子)类型的单字母缩写的 CHECK 约束。包括一个虚拟列,如果两个子类型列都已填充,则该列将“包含”字母“B”。 DDL 代码:
create table kt2 (
key varchar2( 64 ) primary key
, typeL varchar2( 1 )
, typeR varchar2( 1 )
, typeB varchar2( 1 ) generated always as (
case when typeL = 'L' and typeR = 'R' then 'B' else null end
) virtual
, constraint types_check check (
( typeL = 'L' and typeR = 'R' )
or
( typeL = 'L' and typeR is null )
or
( typeL is null and typeR = 'R' )
)
) ;
测试
DBfiddle
insert into kt2 ( key, typeL ) values ( 'AAA', 'L' ) ;
SQL> select * from kt2 ;
KEY TYPEL TYPER TYPEB
AAA L NULL NULL
-- fails (key value must be unique), needs update
insert into kt2 ( key, typeR ) values ( 'AAA', 'R' ) ;
update kt2 set typeR = 'R' where key = 'AAA' ;
SQL> select * from kt2;
KEY TYPEL TYPER TYPEB
AAA L R B
-- cannot insert into B ("generated")
insert into kt2 ( key, typeB ) values ( 'BBB', 'B' ) ;
-- ORA-54013: INSERT operation disallowed on virtual columns
如果你决定走这条路,你可以像这样将旧表(这里的名称:KT)中存储的所有数据转移到新表中:
insert into kt2 ( key )
select unique key from kt -- KT: the old table ;
update kt2
set typeL = 'L'
where key = ( select key from kt where key = kt2.key and type = 'L' )
;
update kt2
set typeR = 'R'
where key = ( select key from kt where key = kt2.key and type = 'R' )
;
编辑(问题更新后)
对原始问题添加的要求:
此外,还保存了其他数据。 L 和 R 可以有
不同的数据。 B是在L和R相同的情况下。所以只有一个
行已保存。
新建议:
表格和约束
create table kt2 (
id number generated always as identity start with 1000 primary key
, key varchar2( 64 )
-- columns for values of type L
, L1 varchar2( 3 ), L2 varchar2( 3 ), L3 varchar2( 3 )
-- columns for values of type R
, R1 varchar2( 3 ), R2 varchar2( 3 ), R3 varchar2( 3 )
-- values for types L and R are identical -> type B
, typeB varchar2( 1 ) generated always as (
case when L1 = R1 and L2 = R2 and L3 = R3 then 'B' else null end
) virtual
, constraint key_typeL_unique unique ( key, L1, L2, L3 )
, constraint key_typeR_unique unique ( key, R1, R2, R3 )
) ;
测试
-- testing: AAA has attribute values for type L and for type R
-- type: L
insert into kt2 ( key, L1, L2, L3 )
values ( 'AAA', 11, 12, 13 ) ;
-- type: R
insert into kt2 ( key, R1, R2, R3 )
values ( 'AAA', 51, 52, 53 ) ;
-- type B: L and R "are the same"
insert into kt2 ( key, L1, L2, L3, R1, R2, R3 )
values ( 'BBB', 14, 15, 16, 14, 15, 16) ;
-- type: L
insert into kt2 ( key, L1, L2, L3 )
values ( 'CCC', 17, 18, 19 ) ;
-- key CCC, type L
-- insert not possible because L exists
insert into kt2 ( key, L1, L2, L3 )
values ( 'CCC', 17, 18, 19 ) ;
-- ORA-00001: unique constraint (...KEY_TYPEL_UNIQUE) violated
-- key BBB type L
-- Not possible because B exists
insert into kt2 ( key, L1, L2, L3 )
values ( 'BBB', 14, 15, 16 ) ;
-- ORA-00001: unique constraint (...KEY_TYPEL_UNIQUE) violated
插入后,表格包含...
SQL> select * from kt2;
ID KEY L1 L2 L3 R1 R2 R3 TYPEB
1000 AAA 11 12 13 NULL NULL NULL NULL
1001 AAA NULL NULL NULL 51 52 53 NULL
1002 BBB 14 15 16 14 15 16 B
1003 CCC 17 18 19 NULL NULL NULL NULL