如何在 oracle 19c 中设置自增复合主键?

How to set an autoincrement composite primary key in oracle19c?

我想在 Oracle 19c 中创建一个具有复合主键和自动增量的 table,如下所示:

pk01 pk02 column1
==== ==== =======
1    1    abc
1    2    def
1    3    ghi
2    1    jkl
2    2    mno
3    1    pqr
1    4    stu

我该怎么做?

在此 table 上创建触发器以实现此结果。假设 table 名字是 test123

create or replace trigger trg_test123 before insert on test123
for each row
declare
v_id1 number;
v_max_id2 number;
begin
v_id1 := :new.id1;
select nvl(max(id2), 0) into v_max_id2 from test123 where id1 = v_id1;
v_max_id2 := v_max_id2 +1;
:new.id2 := v_max_id2;
end;

为什么不创建单列 pk00 作为 pk 并将其设置为自动增量以供存储?即像往常一样插入 pk01 密钥(您需要拥有它)。 table 中没有 pk02,但在使用 window 函数表达式查询时创建它:rank() over (partition by pk01 order by pk00) as pk02.

Table00 pk00 号码 pk pk01号 column1 varchar2(100) ... ...

应用程序的其余部分使用 Table 查询,如下所示。

#######################

drop table table00;

create table table00 (
pk00 NUMBER GENERATED BY DEFAULT AS IDENTITY(START with 1 INCREMENT by 1),
pk01 number,
column1 varchar2(5),
column2 varchar2(5)
);


truncate table table00;

begin
insert into table00(pk01, column1, column2) values(1, 'abc', 'yest');
insert into table00(pk01, column1, column2) values(1, 'def', 'yest');
insert into table00(pk01, column1, column2) values(1, 'ghi', 'yest');
insert into table00(pk01, column1, column2) values(2, 'jkl', 'today');
insert into table00(pk01, column1, column2) values(2, 'mno', 'today');
insert into table00(pk01, column1, column2) values(2, 'pqr', 'today');
insert into table00(pk01, column1, column2) values(1, 'stu', 'yest');
commit;
end;
/

--select * from table00;

select
   --pk00,
   pk01,
   rank() over (partition by pk01 order by pk00) as pk02,
   column1,
   column2
from table00
order by 1,2
;



      PK01       PK02 COLUM COLUM
---------- ---------- ----- -----
         1          1 abc   yest 
         1          2 def   yest 
         1          3 ghi   yest 
         1          4 stu   yest 
         2          1 jkl   today
         2          2 mno   today
         2          3 pqr   today

7 rows selected. 

########################