Delete/Modify 一行 table 基于条件 - Oracle DBMS

Delete/Modify row in one table based on a condition - Oracle DBMS

我有一个 table 结构,如

 create table EMPLOYE (
    CodeEmploye varchar2(100) not null,
    NAS varchar2(100),
    CONSTRAINT employe_pk primary key (CodeEmploye)
);

create table SALAIRE (
    CodeEmploye varchar2(100) not null,
    Mois number not null,
    CONSTRAINT salaire_pk primary key (CodeEmploye, Mois),
    CONSTRAINT salaire_code_employe_fk FOREIGN KEY(CodeEmploye) REFERENCES EMPLOYE(CodeEmploye)
);

我想添加一个约束条件,如果 SALAIRE table.

中存在同一名员工,我将不允许 modify/delete 在 EMPLOYE table 中的一行

最好的方法是什么?

最好的方法之一是在 CREATE TABLE 或 ALTER TABLE 语句期间在 "CodeEmploye" 列上创建外键约束。在您的情况下,它已经作为 CREATE 语句的一部分创建 (salaire_code_employe_fk)。 外键约束确保如果同一雇员存在于子 table (SALAIRE) 中,则来自父 table (EMPLOYE) 的雇员行不能是 modified/deleted。

由于你已经通过"CodeEmployee"列定义了两个table之间的外键关系,你想要的已经实现了。

稍微扩展一下,如果你在fk声明后面加上"ON DELETE CASCADE",一旦你删除employeetable中的任何一行,salarytable中的所有相关记录都会也被删除。

在这种情况下,当您创建 order_items table 时,您使用 DELETE CASCADE 选项定义外键约束,如下所示:

CREATE TABLE order_items   
(  
    order_id   NUMBER( 12, 0 ),   
    -- other columns  
    -- ...  
    CONSTRAINT fk_order_items_orders     
    FOREIGN KEY( order_id )     
    REFERENCES orders( order_id )   
    ON DELETE CASCADE  
);  
By doing this, whenever you delete a row from the orders table, for example:  

DELETE  
FROM  
    orders  
WHERE  
    order_id = 1;  

order_itemstable中order id为1的所有行也被数据库系统自动删除