0

So I have two table with id_pastille and I want to create a trigger that each time that one id_pastille is deleted every table that has the id_pastille is deleted as well.

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 )

and let say this table

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 )
);

I came up with this so far :

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;
1
  • You need to mark your code as such. There are 3 ways to do so. 1. Highlight the code and click the {} above the entry bow. 2. Highlight the code and press Ctrl+K. 3. Place the code between lines contain ``` but otherwise blank. Also, what you places as a answer is actually part of the question ans needs to be places there. Commented May 7, 2021 at 6:04

2 Answers 2

2

You can only delete from a single table in a DELETE statement. Try using several statements.

The best solution might be to define foreign key constraints on all but one of these columns that point to the table that contains the original copy (pastille?). If the foreign key is defined with ON DELETE CASCADE, deleting the original will automatically delete all the dependent rows.

Sign up to request clarification or add additional context in comments.

Comments

0
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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.