`
DavyJones2010
  • 浏览: 154202 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

MySQL: Trigger (Part I)

阅读更多

Target:

    1) Definition of Trigger

    2) Circumstances of Using Trigger

    3) Syntax for Creating Trigger

 

1. Definition of Trigger

    1) Function: Observe one specific state change and then trigger a specific operation.


    Comments:

        1) We want  this to be a transaction: Atomicity

            1) insert into order(goods_id, order_count) values(1, 2); // Ordering

            2) update goods set goods_amount = goods_amount - 2 where goods_id = 1; // Update stock

        2) We want this to be a single operation thant cannot be interrupted.

            We can use transaction to integrate these two operations in JDBC/Hibernate.

            Or we can use trigger to achieve this.

    2) What kind of operation can be monitored by Trigger?

            1) C--->Create

            2) U--->Update

            3) D--->Delete

    3) What kind of operation can be done by Trigger?

            1) C--->Create

            2) U--->Update

            3) D--->Delete

 

2. Circumstances for Using Trigger ---> Some operations that cannot be divided/interrupted. Atomicity!

    1) Ordering -> Update stocking

    2) Credit card overdraw -> Moved into blacklist that cannot overdraw.

 

3. Syntax for Creating Trigger

    1) Which scope to be monitored                            --> Table

    2) What operation to be monitored                        --> CUD

    3) When to be triggered?                                       --> before/after

    4) What operation to be done once be triggered   --> CUD

    Comments: Think about school monitor guard example.

    5) Syntax for Deleting Trigger:          drop trigger trigger_name;

4.

    1) Example 1:  A Simple Hard Code Trigger

# Create initial table
create table goods(goods_id int primary key auto_increment, goods_name varchar(20) not null default '', goods_amount int not null default 0);

create table order_table(order_id int primary key auto_increment, goods_id int, order_count int);

# Aggregate bootstrap data
insert into goods(goods_name, goods_amount) values ('ASUS', 23), ('ThinkPad', 10);
+----------+------------+--------------+
| goods_id | goods_name | goods_amount |
+----------+------------+--------------+
|        1 | ASUS       |           23 |
|        2 | ThinkPad   |           10 |
+----------+------------+--------------+

# Ordering & Updating
insert into order_table(goods_id, order_count) values(2, 2);
update goods set goods_amount = goods_amount - 2 where goods_id = 2;
+----------+------------+--------------+
| goods_id | goods_name | goods_amount |
+----------+------------+--------------+
|        1 | ASUS       |           23 |
|        2 | ThinkPad   |            8 |
+----------+------------+--------------+

# Four essential elements for trigger:
# Scope to be monitored: table order_table;
# Operation to be monitored: insert
# Operation to be done when triggered: update
# Occasion to be triggered: after

# Syntax for Creating Trigger
create trigger trigger_name 
before/after insert/update/delete on table_name
for each row
begin
sql_statement_1;
sql_statement_2;
sql_statement_3;
...;
end;

# Example : Hard Code Just for Explaining Syntax for Creating Trigger
create trigger ordering 
after insert on order_table
for each row
begin
update goods set goods_amount = goods_amount - 2 where goods_id = 2;
end;

# Problems to discuss: begin sql_statement end;
# sql_statement has be be ended with ';'
# But the compiler once encounter ';' will end parsing

# Before creating trigger, change delimiter temporarily
# After creating trigger, recovery delimiter
delimiter $
create trigger ordering
after insert on order_table
for each row
begin
update goods ste goods_amount = goods_amount - 2 where goods_id = 2;
end$

delimiter ;

    2) A More Complicate Trigger:

        1) How to use data which are newly stored in other table?

            1) Insert

                1) For insert statement, the inserted column is tagged as new.

                2) For every single column data in inserted row, tagged as new.column_name. 

# Before trigger creation
select * from goods;
+----------+------------+--------------+
| goods_id | goods_name | goods_amount |
+----------+------------+--------------+
|        1 | ASUS       |           23 |
|        2 | ThinkPad   |            8 |
+----------+------------+--------------+

# Delete previously created trigger
drop trigger ordering;

# Create trigger
delimiter $
create trigger ordering
after insert on order_table
for each row
begin
update goods set goods_amount = goods_amount - new.order_count where goods_id = new.goods_id;
end$

# Recovery delimiter
delimiter ;

# Verify trigger works correctly
insert into order_table(goods_id, order_count) values(1, 3);
select * from goods;
+----------+------------+--------------+
| goods_id | goods_name | goods_amount |
+----------+------------+--------------+
|        1 | ASUS       |           20 |
|        2 | ThinkPad   |            8 |
+----------+------------+--------------+

    3) A Far More Complicate Example 

        1) Requirement:

            1> Every time add an order, subtract corresponding goods number from goods_amount

            2> Every time delete an order, add corresponding goods number to goods_amount

         2) Delete---> Compare with example above about Insert.

            1> For delete statement, the deleted column is tagged as old.

            2> For every single column data in deleted row, tagged as old.column_name. 

# Bootstrap Data
select * from goods;
+----------+------------+--------------+
| goods_id | goods_name | goods_amount |
+----------+------------+--------------+
|        1 | ASUS       |           20 |
|        2 | ThinkPad   |            8 |
+----------+------------+--------------+

select * from order_table;
+----------+----------+-------------+
| order_id | goods_id | order_count |
+----------+----------+-------------+
|        1 |        2 |           2 |
|        2 |        1 |           3 |
+----------+----------+-------------+

# Drop Previous Trigger
drop trigger ordering;

# Change Delimiter Temporarily
delimiter $

# Create Trigger that Monitor Deleting Event on order_table
create trigger del_order
after delete on order_table
for each row
begin
update goods set goods_amount = goods_amount + old.order_count where goods_id = old.goods_id;
end$

# Create Trigger that Monitor Inserting Event on order_table
create trigger add_order
after insert on order_table
for each row
begin
update goods set goods_amount = goods_amount - new.order_count where goods_id = new.goods_id;
end$

# Recovery Delimiter
delimiter ;

# Verify that Insert Trigger works correctly
insert into order_table(goods_id, order_count) values (1, 9);
select * from order_table;
+----------+----------+-------------+
| order_id | goods_id | order_count |
+----------+----------+-------------+
|        1 |        2 |           2 |
|        2 |        1 |           3 |
|        3 |        1 |           9 |
+----------+----------+-------------+
select * from goods;
+----------+------------+--------------+
| goods_id | goods_name | goods_amount |
+----------+------------+--------------+
|        1 | ASUS       |           11 |
|        2 | ThinkPad   |            8 |
+----------+------------+--------------+

# Verify that Delete Trigger works Correctly
delete from order_table where order_id = 1;
select * from order_table;
+----------+----------+-------------+
| order_id | goods_id | order_count |
+----------+----------+-------------+
|        2 |        1 |           3 |
|        3 |        1 |           9 |
+----------+----------+-------------+
select * from goods;
+----------+------------+--------------+
| goods_id | goods_name | goods_amount |
+----------+------------+--------------+
|        1 | ASUS       |           11 |
|        2 | ThinkPad   |           10 |
+----------+------------+--------------+

     4) A Much More Complicate Example 

        1) Requirement:

            1> Every time update an order, update corresponding goods number from goods_amount

         2) Update---> Compare with example above about delete/insert.

# Bootstrap State
select * from order_table;
+----------+----------+-------------+
| order_id | goods_id | order_count |
+----------+----------+-------------+
|        2 |        1 |           3 |
|        3 |        1 |           9 |
+----------+----------+-------------+
select * from goods;
+----------+------------+--------------+
| goods_id | goods_name | goods_amount |
+----------+------------+--------------+
|        1 | ASUS       |           11 |
|        2 | ThinkPad   |           10 |
+----------+------------+--------------+

# Modify Delimiter
delimiter $

# Create Trigger to Monitor Update Operation for order_table
create trigger modify_order
after update on order_table
for each row
begin
update goods set goods_amount = goods_amount + old.order_count - new.order_count where goods_id = old.goods_id;
end$

# Recovery Delimiter
delimiter ;

# Verify this Update Trigger works Correctly
update order_table set order_count = 1 where order_id = 2;
select * from order_table;
+----------+----------+-------------+
| order_id | goods_id | order_count |
+----------+----------+-------------+
|        2 |        1 |           1 |
|        3 |        1 |           9 |
+----------+----------+-------------+
select * from goods;
+----------+------------+--------------+
| goods_id | goods_name | goods_amount |
+----------+------------+--------------+
|        1 | ASUS       |           13 |
|        2 | ThinkPad   |           10 |
+----------+------------+--------------+

# Bingo! Enjoy!

 

Summary:

    How to retrieve/use data when creating trigger?

    1) For insert, the newly inserted row is tagged as new, and each column value in this row tagged as new.column_name;

    2) For delete, the deleted row is tagged as old, and each column value in this row tagged as old.column_name;

    3) For update, the updated row:

        1> Use old to represent the row that is before update.

             Use old.column_name to represent the column value in this row before update.

        2> Use new to represent the row that is after update.

             Use new.column_name to represent the column value in this row after update.

 

Action List:

    1) The difference between before/after?

  • 大小: 32.3 KB
分享到:
评论

相关推荐

    MySQL安装和配置的步骤,适用于Windows系统: Windows系统上安装MySQL: 下载MySQL:

    mysql安装配置教程 MySQL安装和配置的步骤,适用于Windows系统: Windows系统上安装MySQL: 下载MySQL:

    [高可用MySQL:构建健壮的数据中心.].查理斯·贝尔.扫描版.part1

    《高可用MySQL:构建健壮的数据中心》是“MySQL High Availability”的中文翻译版,主要讲解真实环境下如何使用MySQL的复制、集群和监控特性,揭示MySQL可靠性和高可用性的方方面面。《高可用MySQL:构建健壮的数据...

    mysql for liunx 免安装版

    chown -R mysql:mysql /usr/local/mysql/data/ chown -R mysql:mysql /usr/local/mysql/lib/ chown -R mysql:mysql /usr/local/mysql/sock/ 启动:mysql服务 /usr/local/mysql/share/mysql/mysql.server start 进入...

    -bash: mysql: command not found的问题与解决

    前几天重装了mysql,装好之后navicat一直正常可以对mysql进行操作,但是今天要使用命令行进行操作时遇到-bash: mysql: command not found的问题。 总结一下解决办法: 这个问题的出现是两个原因 1 .bash_profile中...

    基于JavaSpring推荐算法新生宿舍管理系统技术框架:前端:html css vue后端:java springboo

    mysql数据库:mysql数据库:mysql数据库:mysql数据库:mysql数据库:mysql数据库:mysql数据库:mysql数据库:mysql数据库:mysql数据库:mysql数据库:mysql数据库:mysql数据库:mysql数据库:mysql数据库:mysql...

    alpine-mysql:Docker镜像MySQL(Alpine)

    MySQL 版本号 高山: 3.7 MySQL的: mariaDB-10.1.28-r1 ...拉: docker pull quay.io/perriea/alpine-mysql:1.0 运行: docker run -d -p 3306:3306 --env-file .env quay.io/perriea/alpine-mysql:1.0

    mysql-connector-java-5.1.47

    MySQL Connector/J 5.1.47 是 MySQL 官方提供的用于Java应用程序连接MySQL数据库的驱动程序,它实现了Java Database Connectivity (JDBC) API。这个工具包是Java开发者与MySQL数据库进行交互的重要桥梁,允许他们...

    Beginning PHP and MySQL: From Novice to Professional, 5th Edition

    Gain skills in MySQL’s fundamental features, including supported data types, database management syntax, triggers, views, stored routine syntax, and import/export capabilities Work with hundreds of...

    mysql-connector-java-8.0.28

    java连接mysql的稳定驱动

    jsp+mysql:动漫网站

    jsp+mysql:毕业设计动漫网站。内含项目代码,数据库脚本。

    mysql-connector-java-5.1.32

    String url = "jdbc:mysql://localhost:3306/mydatabase"; String user = "myuser"; String password = "mypassword"; Connection conn = DriverManager.getConnection(url, user, password); ``` 4. **执行...

    MySQL官方提供的驱动包 mysql-connector-java-5.1.30.zip (亲测可用)

    String url = "jdbc:mysql://localhost:3306/mydatabase"; String user = "username"; String password = "password"; try { Connection conn = DriverManager.getConnection(url, user, password); System....

    mysql-connector-java-8.0.21.jar

    Artifact mysql-connector-java Group mysql Version 8.0.21 Last update 16. June 2020 Newest version Yes Organization Oracle Corporation URL http://dev.mysql.com/doc/connector-j/en/ License The GNU ...

    MYSQL文档完美中文版

    在不同系统中安装MySQL:提供在Windows、Linux、MacOSX、NetWare等平台上的MySQL安装指南。 5.4. 使用源码分发版安装MySQL:解释如何通过源码安装MySQL,包括配置选项和解决编译问题。 5.5. 安装后的设置和测试:...

    mysql连接包mysql-connector-java-5.1.27.jar

    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password"); ``` 3. **SQL执行**:一旦建立了连接,可以创建`Statement`对象来执行SQL查询或更新。例如: ``...

    mysql 安装程序 part3

    本教程将深入探讨MySQL的安装过程,特别关注“part3”,这通常涉及到安装过程的高级步骤和配置选项。MySQL是一个开源的关系型数据库管理系统,以其高效、可靠和易用性而闻名,广泛应用于Web应用、数据分析、数据存储...

    mysql-connector-java.zip 两个版本:5.1.47、8.0.28

    java连接mysql数据库的驱动,里边包含两个版本:5.1.47、8.0.28 也可从以下两个地址免费下载: 1. https://repo1.maven.org/maven2/mysql/mysql-connector-java/ 2. ...

    MySQL运维内参.part2

    MySQL运维内参.part2MySQL运维内参.part2MySQL运维内参.part2MySQL运维内参.part2MySQL运维内参.part2MySQL运维内参.part2MySQL运维内参.part2MySQL运维内参.part2MySQL运维内参.part2

    mysql-connector-java.jar,mysql-essential-5.1.68-win32.zip,mysql安装包

    MySQL是一种广泛使用的开源关系型数据库管理系统(RDBMS),它以其高效、稳定和易于管理的特点在Web开发领域占据了重要地位。MySQL的安装包通常包含了多种组件,以满足不同用户的需求。这里提到的“mysql-connector-...

Global site tag (gtag.js) - Google Analytics