使用MariaDB触发ON DELETE

时间:2014-01-21 18:26:12

标签: sql database triggers mariadb

我有两个表'主题'和'回答':

表1->的主题

+-----+------------+
+  id +   name     +
+=====+============+
+  17 +  question1 +
+-----+------------+
+  18 +  question2 +
+-----+------------+

表2 - >的答案

+----+---------+----------+
+ id + idtopic +   val    +
+----+---------+----------+
+  1 +  17     +  anwer1  +
+----+---------+----------+
+  2 +  18     +  answer2 +
+----+---------+----------+

当我从表'topic'中删除项目时,我只是想创建一个触发器来删除表'answer'中的项目。 如果试过这段代码,但我认为MariaDB语法存在问题:

CREATE TRIGGER delete_answer AFTER DELETE on topic
FOR EACH ROW
BEGIN
DELETE FROM answer
    WHERE answer.idtopic = topic.id;
END

2 个答案:

答案 0 :(得分:1)

这是可以使用的版本。

DELIMITER //
CREATE TRIGGER delete_answer AFTER DELETE on topic
FOR EACH ROW
BEGIN
DELETE FROM answer
    WHERE answer.idtopic = OLD.id;
END
//
DELIMITER ;

答案 1 :(得分:0)

使用OLD关键字来引用正在删除的主题中的当前行。

CREATE TRIGGER delete_answer AFTER DELETE on topic
FOR EACH ROW
BEGIN
DELETE FROM answer
    WHERE answer.idtopic = OLD.id;
END

但是,我想知道为什么你要编写一个触发器而不是使用带有级联删除的外键。你没有在这张桌子上使用InnoDB吗?