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

标签 mysql triggers lastinsertid procedures

我希望在表上创建一个 MySQL 触发器。本质上,我正在创建一个事件流并且需要记录用户的操作。当用户发表评论时,我希望触发该表上的数据库触发器并且:

  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)

关于mysql - 如何编写 MySQL 触发器以将行插入另一个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4753878/

相关文章:

Mysql 5.0 LAST_INSERT_ID()升级到5.6后有所不同

php - Laravel 连接外部数据库?

javascript - 动态表中的 jQuery 表单按钮未检测到第二行以后

php - 如何在 jQuery Mobile 页面中提交表单?

javascript - PHP MySQL 插入数据库

sql - 来自单个更新 SQL 语句的多行更新 SQL 触发器

postgresql - 使用 postgres 触发器清除 APC 缓存

sqlite - sqlite触发器中的条件插入语句

MySQL LAST_INSERT_ID() 与 INSERT INTO 表 SELECT FROM 表

php - PDO lastinsertid 问题