我有3个MySQL表(food
,apple
和orange
)。
我想删除以下行:
apple(idapple, iduser, name)
orange(idornge, iduser, name)
使用一个触发器删除food(iduser, name)
中的行?
到目前为止,这是我的触发器:
CREATE TRIGGER `food_before_delete`
AFTER DELETE ON `food`
FOR EACH ROW
DELETE FROM apple, orange
WHERE
apple.iduser=OLD.iduser and
orange.iduser=OLD.iduser
但它不会编译。如何制作一次从两个表中删除的触发器?
答案 0 :(得分:27)
使用触发器一次从两个表中删除:
触发器用于强制表中的数据完整性。您可以使用触发器一次删除任意数量的表。
在初始化触发器之前,我们需要临时更改mysql定界符运算符,因为触发器使用分号;
运算符在触发器中指定多个sql命令。
步骤1更改当前分隔符:
delimiter $$
步骤2创建触发器:
CREATE TRIGGER `blog_before_delete`
AFTER DELETE ON `blog`
FOR EACH ROW
BEGIN
DELETE FROM blog_tags where blogid = OLD.id;
DELETE FROM blog_comments where blogid = OLD.id;
END
$$
步骤3恢复上一个分隔符:
delimiter ;
<强>解释强>
OLD
是内置关键字,指的是我们要删除的博客表行。每当我们删除博客表中的条目时,Mysql就会运行触发器blog_before_delete
。我的触发器失败,然后回滚删除。这有助于确保我们数据库中的Atomicity, Consistency, Isolation, and Durability。
答案 1 :(得分:3)
CREATE TRIGGER `food_before_delete`
AFTER DELETE ON `food`
FOR EACH ROW
begin
DELETE FROM apple
WHERE apple.iduser=NEW.iduser;
DELETE FROM orange
WHERE orange.iduser=NEW.iduser;
end
delete语句可能需要OLD.iduser,不支持NEW.iduser。查看您的手册。
答案 2 :(得分:1)
可能更简单吗?
DELETE f,a,o FROM
food AS f
LEFT JOIN apple AS a USING (iduser)
LEFT JOIN orange AS o USING (iduser)
WHERE f.name = ...
无需触发器。
答案 3 :(得分:1)
我忘记了触发器中的BEGIN
和END
块。你必须按顺序从表中删除:
CREATE TRIGGER `food_before_delete`
AFTER DELETE ON `food`
FOR EACH ROW
BEGIN
DELETE FROM apple
WHERE apple.iduser=NEW.iduser;
DELETE FROM orange
WHERE orange.iduser=NEW.iduser;
END
答案 4 :(得分:1)
<强> 1。登录强>
el@apollo:~$ mysql -u root -p
Enter password:
mysql> use your_database;
Database changed
<强> 2。创建一些测试表并插入行:
mysql> create table derp(derp1 INT);
Query OK, 0 rows affected (0.02 sec)
mysql> create table foo(foo1 INT);
Query OK, 0 rows affected (0.02 sec)
mysql> create table bar(bar1 INT);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into derp values (1);
Query OK, 1 row affected (0.01 sec)
mysql> insert into foo values (1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into bar values (1);
Query OK, 1 row affected (0.00 sec)
第3。触发:
mysql> delimiter //
mysql> create trigger delete_foo_and_bar_when_derp_is_deleted
-> after delete on derp
-> for each row
-> begin
-> delete from foo where foo1=OLD.derp1;
-> delete from bar where bar1=OLD.derp1;
-> end//
Query OK, 0 rows affected (0.02 sec)
<强> 4。请参阅表格,并填写所有三个。
mysql> delimiter ;
mysql> select * from derp;
+-------+
| derp1 |
+-------+
| 1 |
+-------+
1 row in set (0.00 sec)
mysql> select * from foo;
+------+
| foo1 |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
mysql> select * from bar;
+------+
| bar1 |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
<强> 5。从derp中删除
mysql> delete from derp where derp1 = 1;
Query OK, 1 row affected (0.01 sec)
<强> 6。看到derp,foo和bar现在都是空的:
mysql> select * from derp;
Empty set (0.00 sec)
mysql> select * from foo;
Empty set (0.00 sec)
mysql> select * from bar;
Empty set (0.00 sec)