Oracle 更新一个 table 关于将数据输入另一个 table

Oracle update one table in relation to entering data into another table

场景简单

CREATE TABLE one
(ID NUMBER CONSTRAINT
pk_id PRIMARY KEY,
Number_of_relations INTEGER)

CREATE TABLE two
(mock_id NUMBER,
CONSTRAINT fk_id FOREIGN KEY (mock_id) REFERENCES one(ID)
text VARCHAR)

是否可以在每次输入新行时将Number_of_relations更新为table两行。因此,如果我在 table 中输入 ID 为“1”,此时 Number_of_relations 为“0”,但如果我添加 ('1', 'hello') 和 ('1 ', 'helloagain') 变成 table 两个,现在 id '1' 有两个文本,但我希望 number_of_relations 在 table 中更新(如果可能自动更新)到'2'。有可能吗?,在此先感谢。

这个触发器可以做到:

create or replace trigger ins_two after insert on two
for each row
  update one set number_of_relations = number_of_relations + 1
    where one.id = :new.mock_id

测试:

insert into two values (1, 'hello');
insert into two values (1, 'hello again');
insert into two values (2, 'hello');

select * from one

        ID NUMBER_OF_RELATIONS
---------- -------------------
         1                   2 
         2                   1

这是 INSERT 操作的示例,您还可以添加 DELETE 和 UPDATE 部分。 在 "DELETE" 情况下 number_of_relations 必须递减, 在 "UPDATE" - 这取决于更新的列,但逻辑是相似的。 Triggers 文档和示例。