+--------+-----------+------+-----+-------------------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-----------+------+-----+-------------------+-------+ | uid | int(11) | YES | | NULL | | | action | char(20) | YES | | NULL | | | id | int(11) | YES | | NULL | | | time | timestamp | NO | | CURRENT_TIMESTAMP | | +--------+-----------+------+-----+-------------------+-------+ 4 rows in set (0.01 sec)
创建触发器。由于 MySQL 5.5只支持单事件触发,所以需要三个对应触发器
增
mysql> create trigger user_insert after insert on user -> for each row -> BEGIN -> insert into user_log(uid,action,id) values (new.uid,’create’,new.id); -> END; -> // Query OK, 0 rows affected (0.06 sec)
改
mysql> create trigger user_update after update on user -> for each row -> BEGIN -> insert into user_log(uid,action,id) values (old.uid,’update’,old.id); -> END; -> // Query OK, 0 rows affected (0.05 sec)
删
mysql> create trigger user_delete after delete on user -> for each row -> BEGIN -> insert into user_log(uid,action,id) values (old.uid,’delete’,old.id); -> END; -> // Query OK, 0 rows affected (0.08 sec)
测试:
mysql> select * from user;
Empty set (0.00 sec)
mysql> select * from user_log;
Empty set (0.00 sec)
mysql> insert into user (uid,name,age)values (1000,'aka',10);
Query OK, 1 row affected (0.03 sec)
mysql> insert into user (uid,name,age)values (1000,'mille',19);
Query OK, 1 row affected (0.03 sec)
mysql> insert into user (uid,name,age)values (1003,'jim',22);
Query OK, 1 row affected (0.03 sec)
mysql> update user set name='Sare' where id='1';
Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> delete from user where id=2;
Query OK, 1 row affected (0.03 sec)
结果显示: mysql> select * from user;
1 2 3 4 5 6 7
+----+-------+------+------+ | id | name | age | uid | +----+-------+------+------+ | 1 | Sare | 10 | 1000 | | 3 | jim | 22 | 1003 | +----+-------+------+------+ 2 rows in set (0.00 sec)