首页 > 解决方案 > 多个表的 SQL 删除触发器

问题描述

所以我有两个表,id_pastille我想创建一个触发器,每次id_pastille删除一个触发器时,每个具有该表的表id_pastille也会被删除。

CREATE TABLE tp1_trajet
(
 id_trajet   int NOT NULL,
 longitude   double precision NOT NULL,
 latitude    double precision NOT NULL,
 "date"      timestamp NOT NULL,
 id_pastille int NOT NULL,
 CONSTRAINT PK_zone_geographique PRIMARY KEY ( id_trajet ),
 CONSTRAINT FK_ FOREIGN KEY ( id_pastille ) REFERENCES tp1_pastille ( id_pastille )

让我们说这张桌子

CREATE TABLE tp1_compte
(
 id_compte          int NOT NULL,
 date_achat         date NOT NULL,
 id_pastille        int NOT NULL,
 id_usager          int NOT NULL,
 probabilite_malade double precision NULL,
 CONSTRAINT PK_compte PRIMARY KEY ( id_compte ),
 CONSTRAINT UQ_compte_id_pastille UNIQUE ( id_pastille ),
 CONSTRAINT UQ_compte_id_usager UNIQUE ( id_usager ),
 CONSTRAINT FK_compte_id_pastille FOREIGN KEY ( id_pastille ) REFERENCES tp1_pastille ( id_pastille ),
 CONSTRAINT FK_compte_id_usager FOREIGN KEY ( id_usager ) REFERENCES tp1_usager ( id_usager )
);

到目前为止,我想出了这个:

CREATE FUNCTION Delete_pastille() RETURNS trigger
AS $DeleteCustomerWithOrders$
BEGIN
   DELETE FROM tp1_bulle,
               tp1_compte,
               tp1_pastille,
               tp1_signes_vitaux,
               tp1_usager,
               tp1_transaction,
               tp1_trajet
   WHERE id_pastille = OLD."Id";
   RETURN OLD;
END;
$DeleteCustomerWithOrders$
   LANGUAGE plpgsql;

标签: sqlpostgresqltriggerssql-delete

解决方案


您只能从DELETE语句中的单个表中删除。尝试使用几个语句。

最好的解决方案可能是在指向包含原始副本 ( pastille?) 的表的所有列上定义外键约束,但其中一个列除外。如果外键是用 定义的ON DELETE CASCADE,删除原来的会自动删除所有依赖的行。


推荐阅读