- MySQL 基础
- MySQL - 首页
- MySQL - 简介
- MySQL - 特性
- MySQL - 版本
- MySQL - 变量
- MySQL - 安装
- MySQL - 管理
- MySQL - PHP 语法
- MySQL - Node.js 语法
- MySQL - Java 语法
- MySQL - Python 语法
- MySQL - 连接
- MySQL - Workbench
- MySQL 数据库
- MySQL - 创建数据库
- MySQL - 删除数据库
- MySQL - 选择数据库
- MySQL - 显示数据库
- MySQL - 复制数据库
- MySQL - 数据库导出
- MySQL - 数据库导入
- MySQL - 数据库信息
- MySQL 用户
- MySQL - 创建用户
- MySQL - 删除用户
- MySQL - 显示用户
- MySQL - 修改密码
- MySQL - 授予权限
- MySQL - 显示权限
- MySQL - 收回权限
- MySQL - 锁定用户账户
- MySQL - 解锁用户账户
- MySQL 表
- MySQL - 创建表
- MySQL - 显示表
- MySQL - 修改表
- MySQL - 重命名表
- MySQL - 克隆表
- MySQL - 截断表
- MySQL - 临时表
- MySQL - 修复表
- MySQL - 描述表
- MySQL - 添加/删除列
- MySQL - 显示列
- MySQL - 重命名列
- MySQL - 表锁定
- MySQL - 删除表
- MySQL - 派生表
- MySQL 查询
- MySQL - 查询
- MySQL - 约束
- MySQL - 插入查询
- MySQL - 选择查询
- MySQL - 更新查询
- MySQL - 删除查询
- MySQL - 替换查询
- MySQL - 插入忽略
- MySQL - 插入重复键更新
- MySQL - 插入到选择
- MySQL 运算符和子句
- MySQL - WHERE 子句
- MySQL - LIMIT 子句
- MySQL - DISTINCT 子句
- MySQL - ORDER BY 子句
- MySQL - GROUP BY 子句
- MySQL - HAVING 子句
- MySQL - AND 运算符
- MySQL - OR 运算符
- MySQL - LIKE 运算符
- MySQL - IN 运算符
- MySQL - ANY 运算符
- MySQL - EXISTS 运算符
- MySQL - NOT 运算符
- MySQL - 不等于运算符
- MySQL - IS NULL 运算符
- MySQL - IS NOT NULL 运算符
- MySQL - BETWEEN 运算符
- MySQL - UNION 运算符
- MySQL - UNION 与 UNION ALL
- MySQL - MINUS 运算符
- MySQL - INTERSECT 运算符
- MySQL - INTERVAL 运算符
- MySQL 连接
- MySQL - 使用连接
- MySQL - INNER JOIN
- MySQL - LEFT JOIN
- MySQL - RIGHT JOIN
- MySQL - CROSS JOIN
- MySQL - FULL JOIN
- MySQL - 自连接
- MySQL - 删除连接
- MySQL - 更新连接
- MySQL - UNION 与 JOIN
- MySQL 触发器
- MySQL - 触发器
- MySQL - 创建触发器
- MySQL - 显示触发器
- MySQL - 删除触发器
- MySQL - 插入前触发器
- MySQL - 插入后触发器
- MySQL - 更新前触发器
- MySQL - 更新后触发器
- MySQL - 删除前触发器
- MySQL - 删除后触发器
- MySQL 数据类型
- MySQL - 数据类型
- MySQL - VARCHAR
- MySQL - BOOLEAN
- MySQL - ENUM
- MySQL - DECIMAL
- MySQL - INT
- MySQL - FLOAT
- MySQL - BIT
- MySQL - TINYINT
- MySQL - BLOB
- MySQL - SET
- MySQL 正则表达式
- MySQL - 正则表达式
- MySQL - RLIKE 运算符
- MySQL - NOT LIKE 运算符
- MySQL - NOT REGEXP 运算符
- MySQL - regexp_instr() 函数
- MySQL - regexp_like() 函数
- MySQL - regexp_replace() 函数
- MySQL - regexp_substr() 函数
- MySQL 函数 & 运算符
- MySQL - 日期和时间函数
- MySQL - 算术运算符
- MySQL - 数值函数
- MySQL - 字符串函数
- MySQL - 聚合函数
- MySQL 其他概念
- MySQL - NULL 值
- MySQL - 事务
- MySQL - 使用序列
- MySQL - 处理重复项
- MySQL - SQL 注入
- MySQL - 子查询
- MySQL - 注释
- MySQL - 检查约束
- MySQL - 存储引擎
- MySQL - 将表导出到 CSV 文件
- MySQL - 将 CSV 文件导入数据库
- MySQL - UUID
- MySQL - 公共表表达式
- MySQL - ON DELETE CASCADE
- MySQL - Upsert
- MySQL - 水平分区
- MySQL - 垂直分区
- MySQL - 游标
- MySQL - 存储函数
- MySQL - 信号
- MySQL - 重新发送信号
- MySQL - 字符集
- MySQL - 校对
- MySQL - 通配符
- MySQL - 别名
- MySQL - ROLLUP
- MySQL - 当天日期
- MySQL - 字面量
- MySQL - 存储过程
- MySQL - EXPLAIN
- MySQL - JSON
- MySQL - 标准差
- MySQL - 查找重复记录
- MySQL - 删除重复记录
- MySQL - 选择随机记录
- MySQL - SHOW PROCESSLIST
- MySQL - 更改列类型
- MySQL - 重置自动递增
- MySQL - Coalesce() 函数
- MySQL 有用资源
- MySQL - 有用函数
- MySQL - 语句参考
- MySQL - 快速指南
- MySQL - 有用资源
- MySQL - 讨论
MySQL - 删除后触发器
一般来说,触发器被定义为对事件的响应。在 MySQL 中,触发器被称为特殊的存储过程,因为它不需要像其他存储过程那样显式调用。触发器在所需事件触发时自动执行。触发器分为两种类型:前触发器和后触发器。
这些触发器可以是对表上的插入操作、更新操作或删除操作的响应。因此,这些特殊的存储过程在执行 INSERT、UPDATE 或 DELETE 语句时会做出响应。
MySQL 删除后触发器
删除后触发器是 MySQL 数据库支持的行级触发器。此触发器在从数据库表的一行删除值后立即执行。
行级触发器是一种每次修改一行时都会执行的触发器。对于在表中进行的每个单独事务(如插入、删除、更新操作),一个触发器会自动执行。
当在数据库中执行 DELETE 语句时,首先执行触发器,然后从表中删除所述值。
语法
以下是创建 MySQL 中 AFTER DELETE 触发器的语法:
CREATE TRIGGER trigger_name AFTER DELETE ON table_name FOR EACH ROW BEGIN -- trigger body END;
示例
在此示例中,我们创建一个名为“CUSTOMERS”的表,以演示 AFTER DELETE 触发器,使用以下查询:
CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS VARCHAR(25), SALARY DECIMAL(18, 2), PRIMARY KEY(ID) );
使用以下 INSERT 语句将值插入到此创建的表中:
INSERT INTO CUSTOMERS VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ), (2, 'Khilan', 25, 'Delhi', 1500.00 ), (3, 'Kaushik', 23, 'Kota', 2000.00 ), (4, 'Chaitali', 25, 'Mumbai', 6500.00 ), (5, 'Hardik', 27, 'Bhopal', 8500.00 ), (6, 'Komal', 22, 'MP', 4500.00 ), (7, 'Muffy', 24, 'Indore', 10000.00 );
创建另一个表
现在,让我们创建一个另一个空表来存储所有以前在“CUSTOMERS”主表中删除的客户。
CREATE TABLE OLD_CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS VARCHAR(25), SALARY DECIMAL(18, 2), PRIMARY KEY(ID) );
使用以下 CREATE TRIGGER 语句,在 CUSTOMERS 表上创建一个新的触发器“after_delete_trigger”,以从 CUSTOMERS 表中删除客户详细信息并将它们插入到另一个表“OLD_CUSTOMERS”中:
DELIMITER // CREATE TRIGGER after_delete_trigger AFTER DELETE ON CUSTOMERS FOR EACH ROW BEGIN INSERT INTO OLD_CUSTOMERS VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY); END // DELIMITER ;
使用下面显示的常规 DELETE 语句从 CUSTOMERS 表中删除“旧”客户的详细信息:
DELETE FROM CUSTOMERS WHERE ID = 3;
验证
要验证详细信息是否已从 CUSTOMERS 表中删除并添加到 OLD_CUSTOMERS 表中,让我们尝试使用 SELECT 查询检索它们的两个结果集。
CUSTOMERS 表中的记录如下:
ID | 姓名 | 年龄 | 地址 | 工资 |
---|---|---|---|---|
1 | Ramesh | 32 | Ahmedabad | 2000.00 |
2 | Khilan | 25 | Delhi | 1500.00 |
4 | Chaitali | 25 | Mumbai | 6500.00 |
5 | Hardik | 27 | Bhopal | 8500.00 |
6 | Komal | 22 | Hyderabad | 4500.00 |
7 | Muffy | 24 | Indore | 10000.00 |
OLD_CUSTOMERS 表中的记录如下:
ID | 姓名 | 年龄 | 地址 | 工资 |
---|---|---|---|---|
3 | Kaushik | 23 | Kota | 2000.00 |
如您在上面的表中看到的,数据已从 CUSTOMERS 表中删除并添加到 OLD_CUSTOMERS 表中。但是,在应用程序级别上不可见的唯一区别是触发器在删除完成之后执行,而不是在 BEFORE DELETE 触发器中执行。
使用客户端程序的删除后触发器
我们还可以使用客户端程序而不是 SQL 查询来执行 After Delete 触发器语句。
语法
要通过 PHP 程序执行 After Delete 触发器,我们需要使用 mysqli 函数 query() 查询 CREATE TRIGGER 语句,如下所示:
$sql = "CREATE TRIGGER after_delete_trigger AFTER DELETE ON CUSTOMERS FOR EACH ROW BEGIN INSERT INTO OLD_CUSTOMERS VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY); END"; $mysqli->query($sql);
要通过 JavaScript 程序执行 After Delete 触发器,我们需要使用 mysql2 库的 query() 函数查询 CREATE TRIGGER 语句,如下所示:
sql = `CREATE TRIGGER after_delete_trigger AFTER DELETE ON CUSTOMERS FOR EACH ROW BEGIN INSERT INTO OLD_CUSTOMERS VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY); END`; con.query(sql);
要通过 Java 程序执行 After Delete 触发器,我们需要使用 JDBC 函数 execute() 查询 CREATE TRIGGER 语句,如下所示:
String sql = "CREATE TRIGGER after_delete_trigger AFTER DELETE ON CUSTOMERS FOR EACH ROW BEGIN INSERT INTO OLD_CUSTOMERS VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY); END"; statement.execute(sql);
要通过 python 程序执行 After Delete 触发器,我们需要使用 MySQL Connector/Python 的 execute() 函数查询 CREATE TRIGGER 语句,如下所示:
afterDelete_trigger_query = 'CREATE TRIGGER {trigger_name} AFTER DELETE ON {table_name} FOR EACH ROW BEGIN INSERT INTO {another_table} VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY); END' cursorObj.execute(afterDelete_trigger_query)
示例
以下是程序:
$dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'password'; $db = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db); if ($mysqli->connect_errno) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf('Connected successfully.
'); $sql = "CREATE TRIGGER after_delete_trigger AFTER DELETE ON CUSTOMERS FOR EACH ROW BEGIN INSERT INTO OLD_CUSTOMERS VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY); END"; if ($mysqli->query($sql)) { printf("Trigger created successfully...!\n"); } $q = "DELETE FROM CUSTOMERS WHERE ID = 3"; $result = $mysqli->query($q); if ($result == true) { printf("Delete query executed successfully ...!\n"); } $q1 = "SELECT * FROM CUSTOMERS"; $res1 = $mysqli->query($q1); if ($res1->num_rows > 0) { printf("SELECT * FROM CUSTOMERS(verification): \n"); while ($r1 = $res1->fetch_assoc()) { printf( "Id %d, Name: %s, Age: %d, Address %s, Salary %f", $r1['ID'], $r1["NAME"], $r1['AGE'], $r1["ADDRESS"], $r1["SALARY"], ); printf("\n"); } } $q2 = "SELECT * FROM OLD_CUSTOMERS"; $res2 = $mysqli->query($q2); if ($res2->num_rows > 0) { printf("SELECT * FROM OLD_CUSTOMER(verification): \n"); while ($r1 = $res2->fetch_assoc()) { printf( "Id %d, Name: %s, Age: %d, Address %s, Salary %f", $r1['ID'], $r1["NAME"], $r1['AGE'], $r1["ADDRESS"], $r1["SALARY"], ); printf("\n"); } } if ($mysqli->error) { printf("Error message: ", $mysqli->error); } $mysqli->close();
输出
获得的输出如下:
Trigger created successfully...! Delete query executed successfully ...! SELECT * FROM CUSTOMERS(verification): Id 1, Name: Ramesh, Age: 32, Address Ahmedabad, Salary 2000.000000 Id 2, Name: Khilan, Age: 25, Address Delhi, Salary 1500.000000 Id 4, Name: Chaitali, Age: 25, Address Mumbai, Salary 6500.000000 Id 5, Name: Hardik, Age: 27, Address Bhopal, Salary 8500.000000 Id 6, Name: Komal, Age: 22, Address MP, Salary 4500.000000 Id 7, Name: Muffy, Age: 24, Address Indore, Salary 10000.000000 SELECT * FROM OLD_CUSTOMER(verification): Id 3, Name: Kaushik, Age: 23, Address Kota, Salary 2000.000000
var mysql = require('mysql2'); var con = mysql.createConnection({ host:"localhost", user:"root", password:"password" }); //Connecting to MySQL con.connect(function(err) { if (err) throw err; //console.log("Connected successfully...!"); //console.log("--------------------------"); sql = "USE TUTORIALS"; con.query(sql); sql = `CREATE TRIGGER after_delete_trigger AFTER DELETE ON CUSTOMERS FOR EACH ROW BEGIN INSERT INTO OLD_CUSTOMERS VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY); END`; con.query(sql); console.log("After delete query executed successfully..!"); sql = "DELETE FROM CUSTOMERS WHERE ID = 3"; con.query(sql); console.log("Customers table records: ") sql = "SELECT * FROM CUSTOMERS"; con.query(sql, function(err, result){ if (err) throw err; console.log(result); console.log('---------------------------------'); console.log('OLD_CUSTOMERS table records: ') }); sql = "SELECT * FROM OLD_CUSTOMERS"; con.query(sql, function(err, result){ if (err) throw err; console.log(result); }); });
输出
生成的输出如下:
After delete query executed successfully..! Customers table records: [ { ID: 1, NAME: 'Ramesh', AGE: 32, ADDRESS: 'Ahmedabad', SALARY: '2000.00' }, { ID: 2, NAME: 'Khilan', AGE: 25, ADDRESS: 'Delhi', SALARY: '1500.00' }, { ID: 4, NAME: 'Chaitali', AGE: 25, ADDRESS: 'Mumbai', SALARY: '6500.00' }, { ID: 5, NAME: 'Hardik', AGE: 27, ADDRESS: 'Bhopal', SALARY: '8500.00' }, { ID: 6, NAME: 'Komal', AGE: 22, ADDRESS: 'MP', SALARY: '4500.00' }, { ID: 7, NAME: 'Muffy', AGE: 24, ADDRESS: 'Indore', SALARY: '10000.00' } ] --------------------------------- OLD_CUSTOMERS table records: [ { ID: 3, NAME: 'Kaushik', AGE: 23, ADDRESS: 'Kota', SALARY: '2000.00' } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class AfterDeleteTrigger { public static void main(String[] args) { String url = "jdbc:mysql://127.0.0.1:3306/TUTORIALS"; String user = "root"; String password = "password"; ResultSet rs; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection(url, user, password); Statement st = con.createStatement(); //System.out.println("Database connected successfully...!"); //create table String sql = "CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS VARCHAR(25), SALARY DECIMAL(18, 2), PRIMARY KEY(ID))"; st.execute(sql); System.out.println("Customers table created successfully...!"); //lets insert some records into customers table String sql1 = "INSERT INTO CUSTOMERS VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ), (2, 'Khilan', 25, 'Delhi', 1500.00 ), (3, 'Kaushik', 23, 'Kota', 2000.00 ), (4, 'Chaitali', 25, 'Mumbai', 6500.00 ), (5, 'Hardik', 27, 'Bhopal', 8500.00 ), (6, 'Komal', 22, 'MP', 4500.00 ), (7, 'Muffy', 24, 'Indore', 10000.00 )"; st.execute(sql1); System.out.println("Records inserted successfully...!"); //print table records String sql2 = "SELECT * FROM CUSTOMERS"; rs = st.executeQuery(sql2); System.out.println("Customers table records: "); while(rs.next()) { String id = rs.getString("id"); String name = rs.getString("name"); String age = rs.getString("age"); String address = rs.getString("address"); String salary = rs.getString("salary"); System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Address: " + address + ", Salary: " + salary); } //let create one more table named Old_customers String sql3 = "CREATE TABLE OLD_CUSTOMERS (ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS VARCHAR(25), SALARY DECIMAL(18, 2), PRIMARY KEY(ID))"; st.execute(sql3); System.out.println("OLD_CUSTOMERS table created successully...!"); //print the records String sql4 = "SELECT * FROM OLD_CUSTOMERS"; rs = st.executeQuery(sql4); System.out.println("OLD_CUSTOMERS table records before delete trigger: "); while(rs.next()) { String id = rs.getString("id"); String name = rs.getString("name"); String age = rs.getString("age"); String address = rs.getString("address"); String salary = rs.getString("salary"); System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Address: " + address + ", Salary: " + salary); } //lets create trigger on student table String sql5 = "CREATE TRIGGER after_delete_trigger AFTER DELETE ON CUSTOMERS FOR EACH ROW BEGIN INSERT INTO OLD_CUSTOMERS VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY); END"; st.execute(sql5); System.out.println("Triggerd Created successfully...!"); //lets delete one record from customers table; String d_sql = "DELETE FROM CUSTOMERS WHERE ID = 3"; st.execute(d_sql); System.out.println("Record with id = 3 deleted successfully....!"); //let print OLD_CUSTOMERS table records String sql6 = "SELECT * FROM OLD_CUSTOMERS"; rs = st.executeQuery(sql6); System.out.println("OLD_CUSTOMERS records: "); while(rs.next()) { String id = rs.getString("id"); String name = rs.getString("name"); String age = rs.getString("age"); String address = rs.getString("address"); String salary = rs.getString("salary"); System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Address: " + address + ", Salary: " + salary); } }catch(Exception e) { e.printStackTrace(); } } }
输出
获得的输出如下所示:
Customers table created successfully...! Records inserted successfully...! Customers table records: Id: 1, Name: Ramesh, Age: 32, Address: Ahmedabad, Salary: 2000.00 Id: 2, Name: Khilan, Age: 25, Address: Delhi, Salary: 1500.00 Id: 3, Name: Kaushik, Age: 23, Address: Kota, Salary: 2000.00 Id: 4, Name: Chaitali, Age: 25, Address: Mumbai, Salary: 6500.00 Id: 5, Name: Hardik, Age: 27, Address: Bhopal, Salary: 8500.00 Id: 6, Name: Komal, Age: 22, Address: MP, Salary: 4500.00 Id: 7, Name: Muffy, Age: 24, Address: Indore, Salary: 10000.00 OLD_CUSTOMERS table created successully...! OLD_CUSTOMERS table records before delete trigger: Triggerd Created successfully...! Record with id = 3 deleted successfully....! OLD_CUSTOMERS records: Id: 3, Name: Kaushik, Age: 23, Address: Kota, Salary: 2000.00
import mysql.connector # Establishing the connection connection = mysql.connector.connect( host='localhost', user='root', password='password', database='tut' ) # Creating a cursor object cursorObj = connection.cursor() table_name = 'Customers' another_table = 'OLD_CUSTOMERS' trigger_name = 'after_delete_trigger' afterDelete_trigger_query = f''' CREATE TRIGGER {trigger_name} AFTER DELETE ON {table_name} FOR EACH ROW BEGIN INSERT INTO {another_table} VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY); END ''' cursorObj.execute(afterDelete_trigger_query) print(f"AFTER DELETE Trigger '{trigger_name}' is created successfully.") connection.commit() # Delete details of old customer delete_query = "DELETE FROM Customers WHERE ID = 3;" cursorObj.execute(delete_query) print("Delete query executed successfully.") # close the cursor and connection connection.commit() cursorObj.close() connection.close()
输出
以下是上述代码的输出:
AFTER DELETE Trigger 'after_delete_trigger' is created successfully. Delete query executed successfully.