触发器,一般不要单独调用,主要发生响应的事件mysql会自动调用。
语法:
create trigger 触发器名称 指定执行的时间 on 指定在什么表上执行操作 影响的行数 需要执行的任务或者业务
mysql> desc data
-> ;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
1 row in set (0.01 sec)
mysql> desc chars;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| count | int(10) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.01 sec)
mysql> insert into chars values(0);
Query OK, 1 row affected (0.05 sec)
mysql> create trigger tr1 after insert on data
-> for each row update chars set count=count+char_length(new.name);
Query OK, 0 rows affected (0.20 sec)
mysql> select * from chars;
+-------+
| count |
+-------+
| 0 |
+-------+
1 row in set (0.00 sec)
mysql> insert into data values("jack");
Query OK, 1 row affected (0.09 sec)
mysql> select * from chars;
+-------+
| count |
+-------+
| 4 |
+-------+
1 row in set (0.00 sec)
mysql> insert into data values("cainiao");
Query OK, 1 row affected (0.05 sec)
mysql> select * from chars;
+-------+
| count |
+-------+
| 11 |
+-------+
1 row in set (0.00 sec)
语法:
create trigger 触发器名称 指定执行的时间 on 指定在什么表上执行操作 影响的行数 需要执行的任务或者业务
mysql> desc data
-> ;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
1 row in set (0.01 sec)
mysql> desc chars;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| count | int(10) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.01 sec)
mysql> insert into chars values(0);
Query OK, 1 row affected (0.05 sec)
mysql> create trigger tr1 after insert on data
-> for each row update chars set count=count+char_length(new.name);
Query OK, 0 rows affected (0.20 sec)
mysql> select * from chars;
+-------+
| count |
+-------+
| 0 |
+-------+
1 row in set (0.00 sec)
mysql> insert into data values("jack");
Query OK, 1 row affected (0.09 sec)
mysql> select * from chars;
+-------+
| count |
+-------+
| 4 |
+-------+
1 row in set (0.00 sec)
mysql> insert into data values("cainiao");
Query OK, 1 row affected (0.05 sec)
mysql> select * from chars;
+-------+
| count |
+-------+
| 11 |
+-------+
1 row in set (0.00 sec)