MYSQL - on update one table automatically delete rows in second table - mysql

I have two tables in relation 1:n
create table A (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
data VARCHAR(32),
data2 INTEGER,
INDEX (id)
);
CREATE TABLE B (
A_id BINGINT,
some_data DOUBLE,
INDEX (A_id),
FOREIGN KEY (A_id) REFERENCES A(id) ON DELETE CASCADE
);
If i update a row in table A then i need to delete all records from table B with same id from table A. What is the best way to solve it?
i dont know if i should use a trigger or an event.

You need a trigger on table A:
DELIMITER //
CREATE TRIGGER t BEFORE UPDATE ON A
FOR EACH ROW
BEGIN
DELETE FROM B WHERE a_id = NEW.id;
END
//
DELIMITER ;

Related

MySQL Problem with foreign key on n:m relation

I have this database
create table ticket
(
id int auto_increment primary key,
name varchar(100)
);
create table document
(
id int auto_increment primary key,
name varchar(100)
);
create table ticket_document
(
ticket_id int,
document_id int
);
insert into ticket (id, name) VALUES (1, "a"),(2,"b");
insert into document (id, name) VALUES (1, "x"),(2,"y");
insert into ticket_document (ticket_id, document_id) VALUES (1,1),(1,2),(2,2);
So every ticket can have multiple documents and each document can be referenced to multiple tickets.
I want to achieve, that if I delete a ticket all references to his documents are deleted AND if there is no more reference to one of the document from an other ticket the document is also deleted.
But I don't know how to set the foreign keys.
Create foreign keys:
ALTER TABLE ticket_document
ADD FOREIGN KEY (ticket_id) REFERENCES ticket (id) ON DELETE CASCADE ON UPDATE CASCADE,
ADD FOREIGN KEY (document_id) REFERENCES document (id) ON DELETE CASCADE ON UPDATE CASCADE;
After ticket(s) deletion delete rows from document explicitly (or use service event procedure):
DELETE
FROM document
WHERE NOT EXISTS ( SELECT NULL
FROM ticket_document
WHERE ticket_document.document_id = document.id );
fiddle
Alternatively you may use AFTER DELETE trigger for auto-clearing document table:
CREATE TRIGGER tr_ad_ticket
AFTER DELETE
ON ticket
FOR EACH ROW
DELETE
FROM document
WHERE NOT EXISTS ( SELECT NULL
FROM ticket_document
WHERE ticket_document.document_id = document.id );
fiddle

Trigger not firing in MySQL

I've got a problem with a trigger in MySQL.
My table is the following :
CREATE TABLE IF NOT EXISTS Possessioncartes (
id_carte SMALLINT UNSIGNED,
PRIMARY KEY (id_carte, pseudonyme),
CONSTRAINT fk_inv_carte_id_possession FOREIGN KEY (id_carte) REFERENCES Cartes(id_carte) on delete cascade on update cascade,
pseudonyme VARCHAR(40),
CONSTRAINT fk_inv_carte_pseudo_possession FOREIGN KEY (pseudonyme) REFERENCES Joueurs(pseudonyme) on delete cascade on update cascade,
date_possession DATETIME NOT NULL,
methode_possession VARCHAR(20),
date_non_possession DATETIME,
etat SMALLINT UNSIGNED DEFAULT 1 NOT NULL
);
and my trigger :
create trigger posseder after insert on Possessioncartes
for each row begin
set #date_non_possession = new.date_possession
where #id_carte = new.id_carte;
end$$
( When I add a new card to the table, the trigger should update all the rows that has the same ID )
when I tried to add a new row, I got no errors but no row was updated.
I tried omitting the # but I got an "unknown system variable" error.
Thanks for your time.
Triggers cannot modify the table they are "ON", nor any table involved in the query that triggered them.
For example an update trigger on A, cannot modify B for an update statement like UPDATE A INNER JOIN B ON something SET A.x = somethingelse....

How to ignore foreign constraints and add NULL instead

I have two tables which share same primary/foreign key for ID:
Table1: PRIMARY KEY (id));
Table2: FOREIGN KEY (ident) REFERENCES table1(id);
I am trying to create a trigger in order to let me insert new row with non existing primary key and set on that field NULL but i am getting:
Cannot add or update a child row: a foreign key constraint fails error.
How can i solve this issue ?
this is what i tried but so far:
DELIMITER $$
CREATE TRIGGER t1 BEFORE INSERT on table1
FOR EACH ROW
BEGIN
IF NEW.ident!= (
SELECT ident
FROM dimos
WHERE ident NOT IN (
SELECT id
FROM table1
)
)
THEN
SET NEW.ident = 'NULL';
END IF;
END $$
DELIMITER ;
so i expect to get all field in a row expert the foreign key, foreign key must be null!

trigger to insert value into a parent table when inserting into the child table

I have two tables with the construction below. When I try to add to the books table I get an error that I cannot add or update a child row which I expected. I was hoping that a trigger could be created to add the publisher name to the publisher table before adding to the books table.
This is my first time working with a trigger and I am not sure what I am doing wrong and I can't find an example.
create table publishers
(name varchar(25) not null,
address varchar(55),
phone varchar(12),
PRIMARY KEY(name)
) ENGINE = INNODB;
create table books
(book_id int(4) not null auto_increment,
title varchar(40),
publisher_name varchar(25),
primary key (book_id),
foreign key (publisher_name) references publishers(name) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=INNODB;
and the trigger I am trying to create:
DELIMITER ///
CREATE TRIGGER add_publisher BEFORE insert ON books
FOR EACH ROW
BEGIN
INSERT INTO publishers(name) values (books.pubisher_name);
END;
///
DELIMITER ;
Replace books.publisher_name for NEW.publisher_name.
DELIMITER ///
CREATE TRIGGER add_publisher BEFORE insert ON books
FOR EACH ROW
BEGIN
INSERT INTO publishers(name) values (NEW.publisher_name);
END;
///
DELIMITER ;

create trigger to alter multiple tables

i have n tables,
and each table share a common column 'COLX'. And each table's COLX column can have independent values in that column, but when someone alters value in Main table T's COLX, each table's corresponding COLX value must be updated with new value in T's COLX.
I can only write trigger for one table only, how to write this for n tables?
COLXCascade your triggers through the tables,
table1 will trigger updates to table2,
table2 can then run triggers to affect table3
CREATE TABLE table1 (COLX INT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE table2 (id INT, COLX INT,
INDEX par_ind (parent_id),
FOREIGN KEY (COLX) REFERENCES table1(COLX)
ON UPDATE CASCADE
)