Home Database Mysql Tutorial MySQL触发器的正确使用与案例分析

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

Jun 07, 2016 pm 04:13 PM
mysql use article case analysis correct trigger

以下的文章主要向大家讲述的是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>
Copy after login

希望在表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>
Copy after login

相关的表变为:

<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>
Copy after login

正确的写法

触发器代码

<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>
Copy after login

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>
Copy after login

理解上面代码的关键在于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>
Copy after login

激活触发器后,开始对它进行测试。试着在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>
Copy after login

然后检查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>
Copy after login

如你所见,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>
Copy after login

注意:理想情况下,你还需要一个倒转触发器,每当一个记录从源表格中删除时,它从字符总数中减去记录的字符数。这很容易做到,你可以把它当作练习来完成。提示:应用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>
Copy after login

现在,我想建立一个审计记录来追踪对这个表格所做的改变。这个记录将反映表格的每项改变,并向用户说明由谁做出改变以及改变的时间。我需要建立一个新表格来存储这一信息(表格名: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>
Copy after login

接下来,我将在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>
Copy after login

如果你已经走到这一步,就很容易理解。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>
Copy after login

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

<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>
Copy after login

再来看最后的结果(列表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>
Copy after login

注意,对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>
Copy after login

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


Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 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.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL for Beginners: Getting Started with Database Management MySQL for Beginners: Getting Started with Database Management Apr 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

Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Apr 18, 2025 am 08:42 AM

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.

See all articles