如何编写MySQL触发器以将行插入另一个表?

Eri*_*ric 30 mysql triggers procedures lastinsertid

我想在桌面上创建一个MySQL触发器.基本上,我正在创建一个活动流,需要记录用户的操作.当用户发表评论时,我想要触发该表上的数据库触发器,并且:

  1. 获取最后插入的行的ID(注释行的ID).
  2. 使用上一个插入行中的数据对活动表执行INSERT.

我基本上会复制此触发器以删除注释.

我有的问题:

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

谢谢!自从我触及与DB触发器,程序和功能有关的任何事情以来,已经有几年了.

Jon*_*ack 43

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;
Run Code Online (Sandbox Code Playgroud)

编辑:

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)
Run Code Online (Sandbox Code Playgroud)

  • 对于所有想知道这里的"新"代表什么:_你可以通过使用别名OLD和NEW来引用主题表中的列(与触发器相关联的表).OLD.col_name在更新或删除之前引用现有行的列.NEW.col_name引用要插入的新行的列或更新后的现有行._ http://dev.mysql.com/doc/refman/5.0/en///create-trigger.html (13认同)