如何编程MySQL触发器将行插入到另一个表中?

我正在寻找在表上创build一个MySQL触发器。 实质上,我正在创build一个活动stream,并需要logging用户的操作。 当用户发表评论时,我想让该表上的数据库触发器触发并:

  1. 抓住最后插入的行的ID(注释行的ID)。
  2. 使用来自最后插入的行的数据对活动表执行INSERT。

我将基本上复制这个触发器来删除评论。

我有问题:

  1. LAST_INSERT_ID()是获取id的最好方法吗?
  2. 如何正确地存储最后插入的注释行中的数据,以便在“INSERT into activities”语句中使用?
  3. 我应该使用存储过程的组合以及触发器吗?
  4. 触发器的基本结构是什么样的?

谢谢! 我已经触摸了数据库触发器,程序和函数的任何东西已经有几年了。

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)