`
DavyJones2010
  • 浏览: 154897 次
  • 性别: 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
分享到:
评论

相关推荐

    docker镜像mysql:8.0离线加载包

    docker镜像mysql:8.0,离线加载包 放到这里方便大家使用 亲测这个mysql镜像非常好用 加载方式为 docker load -i mysql.tar 非常方便

    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 进入...

    基于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 跟着三思一步一步学MySQL

    《涂抹MySQL:跟着三思一步一步学MySQL》是一本旨在帮助初学者和中级用户深入理解MySQL数据库系统的教程。这本书通过清晰的解释和实例,逐步引导读者掌握MySQL的核心概念和技术。MySQL是一种广泛使用的开源关系型...

    mysql-connector-java-5.1.47

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

    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 ...

    JDBC:Java连接MySQL数据库(优化版)

    Java连接MySQL数据库(优化版) 目的: 当需要把应用程序从开发环境移植到生产环境时,不用修改源代码,只需要修改mysql.ini配置文件 方法: 不直接把数据库连接信息..."jdbc:mysql://127.0.0.1:3306/dome" jdbc:mysq

    DBD-mysql-3.0008

    DBD-mysql-3.0008 DBD-mysql-3.0008 mysqlhotcopy 需要的这个文件 问题:mysqlhotcopy备份报错 /usr/local/mysql/bin/mysqlhotcopy -u root -p --addtodest --noindices --flushlog -q qeedoo /tmp/bak install_...

    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-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. ...

Global site tag (gtag.js) - Google Analytics