search
HomeDatabaseMysql TutorialMySQL触发器的正确使用与案例分析

MySQL触发器的正确使用与案例分析

Jun 07, 2016 pm 04:13 PM
mysqlusearticlecase analysiscorrecttrigger

以下的文章主要向大家讲述的是MySQL触发器的实际使用详细说明与实际案例分析,同时本文也列举了一些在MySQL触发器的实际式操作中的代码,以下就是文章的详细内容介绍,望大家借鉴。 触发器案例 mysql select*froma;+------+------+------+ |id|name|age|+---

以下的文章主要向大家讲述的是MySQL触发器的实际使用详细说明与实际案例分析,同时本文也列举了一些在MySQL触发器的实际式操作中的代码,以下就是文章的详细内容介绍,望大家借鉴。

触发器案例

<ol class="dp-xml"><li class="alt"><span><span>mysql</span><span class="tag">></span><span> select * from a; +------+------+------+ <br>| id | name | age | +------+------+------+ <br>| 1 | A1 | 10 | | 2 | A2 | 20 | +------+------+------+ <br>mysql</span><span class="tag">></span><span> select * from b; +------+------+------+ <br>| rid | id | age | +------+------+------+ | 5 | 2 | 20 | +------+------+------+  </span></span></li></ol>

希望在表a的age字段更新的时候能够触发表b相应的age字段也更新:

如:

<ol class="dp-xml"><li class="alt"><span><span>update a set </span><span class="attribute">age</span><span class="attribute-value">age</span><span>=age+1 where </span><span class="attribute">id</span><span>=</span><span class="attribute-value">2</span><span>;  </span></span></li></ol>

相关的表变为:

<ol class="dp-xml"><li class="alt"><span><span>mysql</span><span class="tag">></span><span> select * from a; +------+------+------+ <br>| id | name | age | +------+------+------+ <br>| 1 | A1 | 10 | | 2 | A2 | 21 | +------+------+------+ <br>mysql</span><span class="tag">></span><span> select * from b; +------+------+------+ <br>| rid | id | age | +------+------+------+ | 5 | 2 | 21 | +------+------+------+ </span></span></li></ol>

正确的写法

触发器代码

<ol class="dp-xml"><li class="alt"><span><span>CREATE TRIGGER bbs1 AFTER UPDATE ON a FOR EACH ROW update b set </span><span class="attribute">age</span><span>=</span><span class="attribute-value">NEW</span><span>.age where </span><span class="attribute">id</span><span>=</span><span class="attribute-value">NEW</span><span>.id;  </span></span></li></ol>

MySQL触发器

触发器的概念:“在数据库中为响应一个特殊表格中的某些事件而自动执行的程序代码。”(Wikipedia)说得简单一些,它是在一个特殊的数据库事件,如INSERT或DELETE发生时,自动激活的一段代码。触发器可方便地用于日志记录、对单个表格到其他链接式表格进行自动的“层叠式”更改、或保证对表格关系进行自动更新。

当一个新整数值增加到数据库域中时,自动更新运行的总数的代码段是一个触发器。自动记录对一个特殊数据库表格所作更改的SQL命令块也是一个触发器实例。

触发器是MySQL 5.x的新功能,随着5.x代码树新版本的出现,这一功能也逐渐得到改善。在本文中,我将简单介绍如何定义并使用触发器,查看触发器状态,并如何在使用完毕后删除触发器。我还将为你展示一个触发器在现实世界中的应用实例,并检验它对数据库记录的改变。

例子

通过简单(虽然是人为的)实例来说明是了解MySQL触发器应用的最佳办法。首先我们建立两个单域的表格。一个表格中为姓名列表(表格名:data),另一个表格中是所插入字符的字符数(表格名:chars)。我希望在data表格中定义一个触发器,每次在其中插入一个新姓名时,chars表格中运行的总数就会根据新插入记录的字符数目进行自动更新。

<ol class="dp-xml"><li class="alt">
<span><span>mysql</span><span class="tag">></span><span> CREATE TABLE data (name VARCHAR(255)); <br>Query OK, 0 rows affected (0.09 sec) mysql</span><span class="tag">></span><span> CREATE TABLE chars (count INT(10)); <br>Query OK, 0 rows affected (0.07 sec) mysql</span><span class="tag">></span><span> INSERT INTO chars (count) VALUES (0); <br>Query OK, 1 row affected (0.00 sec) mysql</span><span class="tag">></span><span> CREATE TRIGGER t1 <br>AFTER INSERT ON data FOR EACH ROW UPDATE chars SET </span><span class="attribute">count</span><span class="attribute-value">count</span><span> = count + CHAR_LENGTH(NEW.name); Query OK, 0 rows affected (0.01 sec)  </span></span><br> </li></ol>

理解上面代码的关键在于CREATE TRIGGER命令,它被用来定义一个新触发器。这个命令建立一个新触发器,假定的名称为t1,每次有一个新记录插入到data表格中时,t1就被激活。

在这个触发器中有两个重要的子句:

AFTER INSERT子句表明触发器在新记录插入data表格后激活。

UPDATE chars SET count = count + CHAR_LENGTH(NEW.name)子句表示触发器激活后执行的SQL命令。在本例中,该命令表明用新插入的data.name域的字符数来更新 chars.count栏。这一信息可通过内置的MySQL函数CHAR_LENGTH()获得。

放在源表格域名前面的NEW关键字也值得注意。这个关键字表明触发器应考虑域的new值(也就是说,刚被插入到域中的值)。MySQL还支持相应的OLD前缀,可用它来指域以前的值。

你可以通过调用SHOW TRIGGER命令来检查触发器是否被激活。

<ol class="dp-xml"><li class="alt"><span><span>mysql</span><span class="tag">></span><span> SHOW TRIGGERS; *************************** <br>1. row *************************** <br>?Trigger: t1 ?Event: INSERT ?Table: data Statement: <br>UPDATE chars SET </span><span class="attribute">count</span><span class="attribute-value">count</span><span> = count + CHAR_LENGTH(NEW.name) <br>Timing: AFTER ?Created: NULL ql_mode: 1 row in set (0.01 sec)  </span></span></li></ol>

激活触发器后,开始对它进行测试。试着在data表格中插入几个记录:

<ol class="dp-xml"><li class="alt"><span><span>mysql</span><span class="tag">></span><span> INSERT INTO data (name) VALUES ('Sue'), ('Jane'); <br>Query OK, 2 rows affected (0.00 sec) Records: 2?Duplicates: 0?Warnings: 0 </span></span></li></ol>

然后检查chars表格看MySQL触发器是否完成它该完成的任务:

<ol class="dp-xml"><li class="alt"><span><span>mysql</span><span class="tag">></span><span> SELECT * FROM chars; +-------+ <br>| count | +-------+ | 7| +-------+ 1 row in set (0.00 sec) </span></span></li></ol>

如你所见,data表格中的INSERT命令激活触发器,它计算插入记录的字符数,并将结果存储在chars表格中。如果你往data表格中增加另外的记录,chars.count值也会相应增加。

触发器应用完毕后,可有DROP TRIGGER命令轻松删除它。

<ol class="dp-xml"><li class="alt"><span><span>mysql</span><span class="tag">></span><span> DROP TRIGGER t1; Query OK, 0 rows affected (0.00 sec) </span></span></li></ol>

注意:理想情况下,你还需要一个倒转触发器,每当一个记录从源表格中删除时,它从字符总数中减去记录的字符数。这很容易做到,你可以把它当作练习来完成。提示:应用BEFORE DELETE ON子句是其中一种方法。

自写(已测试)

<ol class="dp-xml"><li class="alt"><span><span>mysql</span><span class="tag">></span><span> create trigger t2 before delete on <br>data for each row update chars set </span><span class="attribute">count</span><span class="attribute-value">count</span><span>=count-char_length(old.name); <br>Query OK, 0 rows affected (0.03 sec) </span></span></li></ol>

现在,我想建立一个审计记录来追踪对这个表格所做的改变。这个记录将反映表格的每项改变,并向用户说明由谁做出改变以及改变的时间。我需要建立一个新表格来存储这一信息(表格名:audit),如下所示。(列表C)

列表C

<ol class="dp-xml"><li class="alt"><span><span>mysql</span><span class="tag">></span><span> CREATE TABLE audit (id INT(7), balance FLOAT, <br>user VARCHAR(50) NOT NULL, time TIMESTAMP NOT NULL); <br>Query OK, 0 rows affected (0.09 sec) <br>mysql</span><span class="tag">></span><span> create table accounts(id int(7),label VARCHAR(45),balance float); </span></span></li></ol>

接下来,我将在accounts表格中定义一个MySQL触发器。(列表D)

列表D

<ol class="dp-xml"><li class="alt"><span><span>mysql</span><span class="tag">></span><span> CREATE TRIGGER t3 AFTER UPDATE ON accounts <br>FOR EACH ROW INSERT INTO audit (id, balance, user, time) <br>VALUES (OLD.id, NEW.balance, CURRENT_USER(), NOW()); <br>Query OK, 0 rows affected (0.04 sec) </span></span></li></ol>

如果你已经走到这一步,就很容易理解。accounts表格每经历一次UPDATE,触发器插入(INSERT)对应记录的id、新的余额、当前时间和登录audit表格的用户的名称。

实现中的例子:用触发器审计记录

既然你了解了触发器的基本原理,让我们来看一个稍稍复杂的例子。我们常用触发器来建立一个自动“审计记录”,以记录各种用户对数据库的更改。为了解审计记录的实际应用,请看下面的表格(表格名:accounts),它列出了一个用户的三个银行账户余额。(表A)

表A

<ol class="dp-xml"><li class="alt"><span><span>mysql</span><span class="tag">></span><span> SELECT * FROM accounts; +----+------------+---------+ <br>| id | label| balance | +----+------------+---------+ <br>|1 | Savings #1 |500 | |2 | Current #1 |2000 | |3 | <br>Current #2 |3500 | +----+------------+---------+ 3 rows in set (0.00 sec) </span></span></li></ol>

然后,检查触发器是否被激活:

<ol class="dp-xml"><li class="alt"><span><span>mysql</span><span class="tag">></span><span> SHOW TRIGGERS ; *************************** <br>1. row *************************** ?Trigger: t1 ?Event: <br>UPDATE ?Table: accounts Statement: INSERT INTO audit (id, balance, user, time) <br>VALUES (OLD.id, NEW.balance, CURRENT_USER(), NOW()) Timing: AFTER ?Created: NULL Sql_mode: 1 row in set (0.01 sec) </span></span></li></ol>

再来看最后的结果(列表E):

列表E

<ol class="dp-xml"><li class="alt"><span><span>mysql</span><span class="tag">></span><span> UPDATE accounts SET </span><span class="attribute">balance</span><span> = </span><span class="attribute-value">500</span><span> WHERE </span><span class="attribute">id</span><span> = <br></span><span class="attribute-value">1</span><span>; Query OK, 1 row affected (0.00 sec) Rows matched: <br>1?Changed: 1?Warnings: 0 mysql</span><span class="tag">></span><span> UPDATE accounts SET <br></span><span class="attribute">balance</span><span> = </span><span class="attribute-value">900</span><span> WHERE </span><span class="attribute">id</span><span> = </span><span class="attribute-value">3</span><span>; Query OK, 1 row affected <br>(0.01 sec) Rows matched: 1?Changed: 1?Warnings: 0 mysql</span><span class="tag">></span><span> <br>UPDATE accounts SET </span><span class="attribute">balance</span><span> = </span><span class="attribute-value">1900</span><span> WHERE </span><span class="attribute">id</span><span> = </span><span class="attribute-value">1</span><span>; Query OK, <br>1 row affected (0.00 sec) Rows matched: 1?Changed: 1?Warnings: 0  </span></span></li></ol>

注意,对accounts表格所作的改变已被记录到audit表格中,将来如果出现问题,我们可以方便地从中进行恢复。

<ol class="dp-xml"><li class="alt"><span><span>mysql</span><span class="tag">></span><span> SELECT * FROM audit; +------+---------+----------------+---------------------+ <br>| id| balance | user| time| +------+---------+----------------+---------------------+ <br>|1 |500 | root@localhost | 2006-04-22 12:52:15 | |3 |900 | root@localhost | 2006-04-22 12:53:15 <br>| |1 |1900 | root@localhost | 2006-04-22 12:53:23 | +------+---------+----------------+---------------------+ 3 rows in set (0.00 sec)  </span></span></li></ol>

如上面的例子所示,MySQL触发器是一个强大的新功能,它大大增强了RDBMS的自动化程度。自己去试验,练习吧!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.