如何解决多表的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;
解决方法
您只能在 DELETE
语句中从单个表中删除。尝试使用多个语句。
最好的解决方案可能是在这些列中的所有列上定义外键约束,这些列指向包含原始副本 (pastille
?) 的表。如果外键是用ON DELETE CASCADE
定义的,删除原来的会自动删除所有依赖的行。
alter table tp1_trajet
drop constraint fK_,add constraint fK_
foreign key (ID_pastille)
references tp1_pastille (ID_pastille)
on delete cascade;
alter table tp1_compte
drop constraint FK_compte_id_pastille,add constraint FK_compte_id_pastille
foreign key (ID_pastille)
references tp1_pastille (ID_pastille)
on delete cascade;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。