Reputation: 123
I have two tables 'topic' and 'answer':
Table 1-> topic
+-----+------------+
+ id + name +
+=====+============+
+ 17 + question1 +
+-----+------------+
+ 18 + question2 +
+-----+------------+
Table 2 -> answer
+----+---------+----------+
+ id + idtopic + val +
+----+---------+----------+
+ 1 + 17 + anwer1 +
+----+---------+----------+
+ 2 + 18 + answer2 +
+----+---------+----------+
I'm simply trying to create a trigger to delete items from table 'answer', when deleting items from table 'topic'. If tried this code, but there is problem with MariaDB syntax I think:
CREATE TRIGGER delete_answer AFTER DELETE on topic
FOR EACH ROW
BEGIN
DELETE FROM answer
WHERE answer.idtopic = topic.id;
END
Upvotes: 0
Views: 2958
Reputation: 51
Here is the version that will work.
DELIMITER //
CREATE TRIGGER delete_answer AFTER DELETE on topic
FOR EACH ROW
BEGIN
DELETE FROM answer
WHERE answer.idtopic = OLD.id;
END
//
DELIMITER ;
Upvotes: 1
Reputation: 562811
Use the OLD
keyword to refer to the current row in topic that is being deleted.
CREATE TRIGGER delete_answer AFTER DELETE on topic
FOR EACH ROW
BEGIN
DELETE FROM answer
WHERE answer.idtopic = OLD.id;
END
However, I wonder why you're writing a trigger instead of using a foreign key with cascading delete. Are you not using InnoDB for this table?
Upvotes: 0