mysql触发器的应用

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
mysql> desc test;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | char(20) | NO | PRI | | |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> desc haha;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> select * from test;
Empty set (0.00 sec)
mysql> select * from haha;
Empty set (0.00 sec)
########### insert #############
delimiter $$
drop trigger if exists test$$
create trigger test
after
insert on test for each row
begin
insert into haha
values (new.id,new.name);
end$$
delimiter ;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
mysql> insert into test values (1,'test');
Query OK, 1 row affected (0.00 sec)
mysql> select * from test;
+----+------+
| id | name |
+----+------+
| 1 | test |
+----+------+
1 row in set (0.00 sec)
mysql> select * from haha;
+----+------+
| id | name |
+----+------+
| 1 | test |
+----+------+
1 row in set (0.00 sec)
########### update ##############
delimiter $$
drop trigger if exists test$$
create trigger test
after
update on test for each row
begin
update haha set id=new.id;
end$$
delimiter ;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
mysql> update test set id=100;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from haha;
+-----+------+
| id | name |
+-----+------+
| 100 | test |
+-----+------+
1 row in set (0.00 sec)
mysql> select * from test;
+-----+------+
| id | name |
+-----+------+
| 100 | test |
+-----+------+
1 row in set (0.00 sec
########### delete ##############
delimiter $$
drop trigger if exists test$$
create trigger test
after
delete on test for each row
begin
delete from haha where id=old.id and name=old.name;
end$$
delimiter ;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@
mysql> delete from test where id=1 and name='test';
Query OK, 1 row affected (0.02 sec)
mysql> select * from test;
Empty set (0.00 sec)
mysql> select * from haha;
Empty set (0.00 sec)
################ 参照完整性约束 ###################
delimiter $$
drop trigger if exists test$$
create trigger test
before
insert on test for each row
begin
declare a int default 0;
select id into a from test where id=new.id;
if a<=10
then
rollback work;
end if;
end;
end$$
delimiter ;

你可能感兴趣的:(触发器,mysql,数据库,应用,休闲)