2011-01-20 88 views
24

我正在寻找在表上创建一个MySQL触发器。实质上,我创建一个活动流并需要记录用户的操作。当用户发表评论时,我想让该表上的数据库触发器触发:如何编写MySQL触发器将行插入另一个表中?

  1. 获取最后插入行的ID(注释行的ID)。
  2. 使用来自最后一个插入行的数据,将INSERT执行到活动表中。

我基本上会复制这个触发器来删除注释。

问题我有:

  1. 是LAST_INSERT_ID()来获取ID的最佳方式?
  2. 如何正确存储上次插入的评论行中的数据以便在“INSERT into activities”语句中使用?
  3. 我是否应该使用存储过程的组合以及触发器?
  4. 触发器的基本结构是什么样的?

谢谢!自从我触及与数据库触发器,程序和函数有关的事情已经有几​​年了。

回答

36
drop table if exists comments; 
create table comments 
(
comment_id int unsigned not null auto_increment primary key, 
user_id int unsigned not null 
) 
engine=innodb; 

drop table if exists activities; 
create table activities 
(
activity_id int unsigned not null auto_increment primary key, 
comment_id int unsigned not null, 
user_id int unsigned not null 
) 
engine=innodb; 

delimiter # 

create trigger comments_after_ins_trig after insert on comments 
for each row 
begin 
    insert into activities (comment_id, user_id) values (new.comment_id, new.user_id); 
end# 

delimiter ; 

insert into comments (user_id) values (1),(2); 

select * from comments; 
select * from activities; 

编辑:

mysql> \. d:\foo.sql 

Database changed 
Query OK, 0 rows affected (0.10 sec) 

Query OK, 0 rows affected (0.30 sec) 

Query OK, 0 rows affected (0.11 sec) 

Query OK, 0 rows affected (0.35 sec) 

Query OK, 0 rows affected (0.07 sec) 

Query OK, 2 rows affected (0.03 sec) 
Records: 2 Duplicates: 0 Warnings: 0 

+------------+---------+ 
| comment_id | user_id | 
+------------+---------+ 
|   1 |  1 | 
|   2 |  2 | 
+------------+---------+ 
2 rows in set (0.00 sec) 

+-------------+------------+---------+ 
| activity_id | comment_id | user_id | 
+-------------+------------+---------+ 
|   1 |   1 |  1 | 
|   2 |   2 |  2 | 
+-------------+------------+---------+ 
2 rows in set (0.00 sec) 
+7

对于所有想知道什么是“新”在这里是一个代表:_You可以通过使用引用列主题表格(与触发器关联的表)别名OLD和NEW。 OLD.col_name在更新或删除之前引用现有行的列。 NEW.col_name引用要插入的新行的列或更新后的现有行的列._ http://dev.mysql.com/doc/refman/5.0/en///create-trigger.html – SimonSimCity 2013-05-27 09:32:02

相关问题