我想要一个触发器从 MySQL 中的 2 个表中删除

I want a trigger to DELETE from 2 tables in MySQL(我想要一个触发器从 MySQL 中的 2 个表中删除)
本文介绍了我想要一个触发器从 MySQL 中的 2 个表中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个 MySQL 表(foodappleorange).

I have 3 MySQL tables (food, apple, and orange).

我想从以下位置删除行:

I want to delete rows from:

apple(idapple, iduser, name) 
orange(idornge, iduser, name)

当使用一个触发器删除food(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?

推荐答案

使用触发器一次从两个表中删除:

触发器用于强制执行表中的数据完整性.您可以使用触发器一次从任意数量的表中删除.

Triggers are used to enforce data integrity in the tables. You can use triggers to delete from any number of tables at once.

在初始化触发器之前,我们需要临时更改mysql分隔符运算符,因为触发器使用分号;运算符来指定触发器内的多个sql命令.

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.

第 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.我触发器失败,然后删除被回滚.这有助于确保我们数据库中的原子性、一致性、隔离性和持久性.

OLD is a builtin keyword and refers to the blog table row that we are deleting. Mysql runs the trigger blog_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.

这篇关于我想要一个触发器从 MySQL 中的 2 个表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)