mysql触发器(Trigger)简明总结和使用实例_MySQL
一,什么触发器
1,个人理解
触发器,从字面来理解,一触即发的一个器,简称触发器(哈哈,个人理解),举个例子吧,好比天黑了,你开灯了,你看到东西了。你放炮仗,点燃了,一会就炸了。
2,官方定义
触发器(trigger)是个特殊的存储过程,它的执行不是由程序调用,也不是手工启动,而是由事件来触发,比如当对一个表进行操作( insert,delete, update)时就会激活它执行。触发器经常用于加强数据的完整性约束和业务规则等。 触发器可以从 DBA_TRIGGERS ,USER_TRIGGERS 数据字典中查到。
触发器有一个非常好的特性就是:触发器可以禁止或回滚违反引用完整性的更改,从而取消所尝试的数据修改。
什么意思,举个例子解释一下,街机游戏大家都玩过吧,闯过一关,闯下一关,有一关没闯过就要从第一关开始。触发器根这个类似。
官方解释如下
触发程序视为单一交易中的一部份,因此可以由原触发程序还原交易,如果在交易过程中侦测到严重的错误(如使用者中断连线),则会自动还原整个交易。
他的作用很明显了,可以保重数据的完整性,下面有一个实例来说明他的好处,以及如果使编写代码不那么复杂
二,触发器语法
CREATE TRIGGER trigger_name trigger_time trigger_event
ON tbl_name FOR EACH ROW trigger_stmt
触发程序是与表有关的命名数据库对象,当表上出现特定事件时,将激活该对象。
触发程序与命名为tbl_name的表相关。tbl_name必须引用永久性表。不能将触发程序与TEMPORARY表或视图关联起来。
trigger_time是触发程序的动作时间。它可以是BEFORE或AFTER,以指明触发程序是在激活它的语句之前或之后触发。
trigger_event指明了激活触发程序的语句的类型。trigger_event可以是下述值之一:
INSERT:将新行插入表时激活触发程序,例如,通过INSERT、LOAD DATA和REPLACE语句。
UPDATE:更改某一行时激活触发程序,例如,通过UPDATE语句。
DELETE:从表中删除某一行时激活触发程序,例如,通过DELETE和REPLACE语句。
请注意,trigger_event与以表操作方式激活触发程序的SQL语句并不很类似,这点很重要。例如,关于INSERT的BEFORE触发程序不仅能被INSERT语句激活,也能被LOAD DATA语句激活。
可能会造成混淆的例子之一是INSERT INTO .. ON DUPLICATE UPDATE ...语法:BEFORE INSERT触发程序对于每一行将激活,后跟AFTER INSERT触发程序,或BEFORE UPDATE和AFTER UPDATE触发程序,具体情况取决于行上是否有重复键。
对于具有相同触发程序动作时间和事件的给定表,不能有两个触发程序。例如,对于某一表,不能有两个BEFORE UPDATE触发程序。但可以有1个BEFORE UPDATE触发程序和1个BEFORE INSERT触发程序,或1个BEFORE UPDATE触发程序和1个AFTER UPDATE触发程序。
trigger_stmt是当触发程序激活时执行的语句。如果你打算执行多个语句,可使用BEGIN ... END复合语句结构。这样,就能使用存储子程序中允许的相同语句
三,创建解发器
1,用户表user
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment COMMENT '用户ID',
`name` varchar(50) NOT NULL default '' COMMENT '名称',
`sex` int(1) NOT NULL default '0' COMMENT '0为男,1为女',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
INSERT INTO `user` (`id`, `name`, `sex`) VALUES
(1, '张映', 0),
(2, 'tank', 0);
2,评论表comment
CREATE TABLE `comment` (
`c_id` int(11) NOT NULL auto_increment COMMENT '评论ID',
`u_id` int(11) NOT NULL COMMENT '用户ID',
`name` varchar(50) NOT NULL default '' COMMENT '用户名称',
`content` varchar(1000) NOT NULL default '' COMMENT '评论内容',
PRIMARY KEY (`c_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
INSERT INTO `comment` (`c_id`, `u_id`, `name`, `content`) VALUES
(1, 1, '张映', '触发器测试'),
(2, 1, '张映', '解决字段冗余'),
(3, 2, 'tank', '使代码更简单');
在这里有一个冗余字段name,我们在读取评论进可以用联合查寻来找到user表中的名字,为什么要有冗余字段呢,因简单的sql语句执行效率更高,但不是冗余字段越多越好,冗余字段多了,同样会增加数据库负担 .
我要做的事情是,当我更新user表的name时,触发器同时更新comment表,就不要写php代码去更新了,当用户被删除时,comment表中,有关该用户的数据将被删除
3,更新name触发器
delimiter || //mysql 默认结束符号是分号,当你在写触发器或者存储过程时有分号出现,会中止转而执行
drop trigger if exists updatename|| //删除同名的触发器,
create trigger updatename after update on user for each row //建立触发器,
begin
//old,new都是代表当前操作的记录行,你把它当成表名,也行;
if new.name!=old.name then //当表中用户名称发生变化时,执行
update comment set comment.name=new.name where comment.u_id=old.id;
end if;
end||
delimiter ;
4,触发器删除comment数据
delimiter ||
drop trigger if exists deletecomment||
create trigger deletecomment before delete on user for each row
begin
delete from comment where comment.u_id=old.id;
end||
delimiter ;
有一点很让人郁闷,就是写好的触发器代码,不能修改,你要删除掉重建,郁闷中,对了还有一点就是phpmyadmin,有的能创建触发器,有的不能,有的能创建,但创建了看不到。在研究一下。
5,测试触发器是否可用
a,测试updata触发器
update user set name='苍鹰' where id = 1;
更新后去comment表里面看看,里面name字段里面的段有没有改变
b,测试delete触发器
delete from user where id = 1;
更新后去comment表里面看看,里面name字段里面的段有没有改变
四,触发器的优点
1,触发器的"自动性"
对程序员来说,触发器是看不到的,但是他的确做事情了,如果不用触发器的话,你更新了user表的name字段时,你还要写代码去更新其他表里面的冗余字段,我举例子,只是一张表,如果是几张表都有冗余字段呢,你的代码是不是要写很多呢,看上去是不是很不爽呢。
2,触发器的数据完整性
触发器有回滚性,举个例子,我发现我很喜欢举子,就是你要更新五张表的数据,不会出现更新了二个张表,而另外三张表没有更新。
但是如果是用php代码去写的话,就有可能出现这种情况的,比如你更新了二张表的数据,这个时候,数据库挂掉了。你就郁闷了,有的更新了,有的没更新。这样页面显示不一致了,变有bug了。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

Recovering deleted rows directly from the database is usually impossible unless there is a backup or transaction rollback mechanism. Key point: Transaction rollback: Execute ROLLBACK before the transaction is committed to recover data. Backup: Regular backup of the database can be used to quickly restore data. Database snapshot: You can create a read-only copy of the database and restore the data after the data is deleted accidentally. Use DELETE statement with caution: Check the conditions carefully to avoid accidentally deleting data. Use the WHERE clause: explicitly specify the data to be deleted. Use the test environment: Test before performing a DELETE operation.

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.
