Mysql触发器插入两个连接的表

时间:2014-08-03 16:05:11

标签: mysql database triggers

我有3个mysql表:

user_followers 的列ID为user_id 通知的列ID为user_id notification_object 包含列notification_id,类型

在我要插入的user_followers上插入

user_id =通知中的New.user_id

然后使用刚刚插入的通知ID

notification_object.type =" 2"和notification_object.notification_id =只是在通知表中插入了id

现在问题是如何找到通知表的id:

DELIMITER //


CREATE TRIGGER follow_notification AFTER INSERT ON user_friends
FOR EACH ROW 
Begin
insert into notification(user_id) values(New.user_id);
insert into notification_object(notification_id,type) values(????,"2");

End

//

1 个答案:

答案 0 :(得分:0)

如果notifications.id自动递增,则mysql包含一个函数last_insert_id(),它将返回(with caveats)最后插入的id。

DELIMITER //

CREATE TRIGGER follow_notification AFTER INSERT ON user_friends
FOR EACH ROW 
Begin
  declare v_notification_id INT;
  insert into notification(user_id) values(New.user_id);
  /* set a variable to the last id inserted to the db */
  set v_notification_id=(select last_insert_id());
  /* use the variable in the next insert */
  insert into notification_object(notification_id,type) values(v_notification_id,"2");

End//