我想要一个触发器从 MySQL 中的 2 个表中删除
我有 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
但它不会编译。如何制作一个同时从两个表中删除的触发器?
I have 3 MySQL tables (food
, apple
, and orange
).
I want to delete rows from:
apple(idapple, iduser, name)
orange(idornge, iduser, name)
When deleting a row in food(iduser, name)
using one trigger?
Here is my trigger so far:
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
But it won't compile. How can make a trigger that deletes from two tables at once?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用触发器同时删除两个表:
触发器用于强制表中数据的完整性。您可以使用触发器一次从任意数量的表中删除。
在初始化触发器之前,我们需要暂时更改mysql分隔符运算符,因为触发器使用分号
;
运算符来指定触发器内的多个sql命令。第 1 步更改当前分隔符:
第 2 步创建触发器:
第 3 步恢复先前的分隔符:
说明:
OLD
是一个内置关键字,指的是我们要删除的博客表行。每当我们删除博客表中的条目时,Mysql 就会运行触发器blog_before_delete
。如果触发器失败,则回滚删除。这有助于确保我们的数据库的原子性、一致性、隔离性和持久性。Delete from two tables at once with a Trigger:
Triggers are used to enforce data integrity in the tables. You can use triggers to delete from any number of tables at once.
Before initializing triggers we need to change the mysql delimiter operator temporarily because triggers use semicolon
;
operator to specify multiple sql commands within the trigger.Step 1 Change current delimiter:
Step 2 Create trigger:
Step 3 Restore previous delimiter:
Explanation:
OLD
is a builtin keyword and refers to the blog table row that we are deleting. Mysql runs the triggerblog_before_delete
whenever we delete an entry in the blog table. I the trigger fails, then the delete is rolled back. This helps ensure Atomicity, Consistency, Isolation, and Durability in our database.删除语句可能需要 OLD.iduser,但不支持 NEW.iduser。检查你的手册。
The delete statements may require OLD.iduser and not support NEW.iduser. Check your manual.
也许更简单的东西?
无需触发器。
Something simpler maybe?
No trigger needed.
我忘记了触发器中的
BEGIN
和END
块。并且您必须按顺序从表中删除,如下所示:I forgot the
BEGIN
andEND
blocks in the trigger. And you have to delete from tables sequentially like this:MySQL 演练如何制作一个触发器,用一个触发器删除两个表:
1.登录:
2.创建一些测试表并插入行:
3.触发触发器:
4.查看表是否存在并且所有三个表均已填充。
5.从derp中删除
6.看到 derp、foo 和 bar 现在都是空的:
MySQL walkthrough of making a trigger to delete two tables with one trigger:
1. Login:
2. Create some test tables and insert rows:
3. Make the trigger:
4. See the tables exist and all three are populated.
5. Delete from derp
6. See that derp, foo, and bar are empty now: