简体   繁体   English

sql中的外键:Oracle

[英]foreign key in sql : Oracle

Parent Table 父表

id | id | name /// id primary key 名称/// id主键

1 | 1 | Quddus 库杜斯

Child Table 子表

id | id | name /// id primary key as well as foreign key 名称/// id主键以及外键

1 | 1 | Quddus 库杜斯

Here , I have used on delete cascade . 在这里,我已经使用了删除级联。 Thats why , if I delete any tuple from parent table , it's also deleted from child table . 这就是为什么如果我从父表中删除任何元组,它也从子表中删除的原因。 But if I try to update the id in parent table , it does not effect child table rather say ERROR! 但是,如果我尝试更新父表中的ID,则不会影响子表,而是会提示ERROR!

So my question is by which way i can update parent table and child table at the same time . 所以我的问题是,通过哪种方式可以同时更新父表和子表。

Thanks! 谢谢! and Sorry cause I am not a good English writer ! 对不起,因为我不是一个好的英语作家!

There is no " on update cascade" in Oracle. 在Oracle中没有“更新级联”。 You should write a trigger for update child table when you update parent table. 更新父表时,应为更新子表编写触发器 look this site. 看这个网站。 you'll see example trigger for you. 您会看到示例触发器。 just write a trigger. 只需编写一个触发器。 https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:5773459616034 https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:5773459616034

This looks like a bad design. 这看起来像一个不好的设计。 If the child table's ID should follow the parent table's ID then why do you have a child table at all? 如果子表的ID应该跟在父表的ID之后,那么为什么还要有一个子表呢? You might just as well add the child table's columns to the parent table. 您也可以将子表的列添加到父表中。

In a more common design the child table will have it's own ID (PK) column and another ID_Parent column to reference the parent table. 在更常见的设计中,子表将具有其自己的ID(PK)列和另一个ID_Parent列来引用父表。

Also unusual is the need to update a PK column. 同样不寻常的是需要更新PK列。 Actually that's a definite NO. 实际上,这是绝对不可以。

Unfortunately there is nothing called cascade update in Oracle. 不幸的是,Oracle中没有所谓的级联更新。 So what you have to do is to create a trigger and then do the update: 因此,您要做的就是创建一个触发器,然后进行更新:

CREATE TABLE t1(c1 number primary key);
CREATE TABLE t2(c2 number references t1(

INSERT INTO t1 VALUES(1);
INSERT INTO t2 VALUES(1);

CREATE TRIGGER Cascade_Update
    AFTER UPDATE OF c1 ON t1
    FOR EACH ROW
BEGIN
    UPDATE t2
    SET c2 = :new.c1
    WHERE c2 = :old.c1;
END;

Now do the update and it'll update the child table too. 现在进行更新,它也会更新子表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM