开发者社区> 问答> 正文

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

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

抓住最后插入的行的ID(注释行的ID)。 使用最后插入的行中的数据对活动表执行INSERT。 实际上,我将复制此触发器以删除评论。

我的问题:

LAST_INSERT_ID()是获取ID的最佳方法吗? 如何正确存储最后插入的注释行中的数据,以便在我的“插入活动”语句中使用? 我应该同时使用存储过程和触发器吗? 触发器的基本结构是什么样的? 谢谢!自从我接触到与DB触发器,过程和函数有关的一切以来已经有几年了。

展开
收起
保持可爱mmm 2020-05-17 10:34:24 413 0
1 条回答
写回答
取消 提交回答
  • 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)来源:stack overflow

    2020-05-17 10:47:41
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
搭建电商项目架构连接MySQL 立即下载
搭建4层电商项目架构,实战连接MySQL 立即下载
PolarDB MySQL引擎重磅功能及产品能力盛大发布 立即下载

相关镜像