2011-01-20 86 views
24

我正在尋找在表上創建一個MySQL觸發器。實質上,我創建一個活動流並需要記錄用戶的操作。當用戶發表評論時,我想讓該表上的數據庫觸發器觸發:如何編寫MySQL觸發器將行插入另一個表中?

  1. 獲取最後插入行的ID(註釋行的ID)。
  2. 使用來自最後一個插入行的數據,將INSERT執行到活動表中。

我基本上會複製這個觸發器來刪除註釋。

問題我有:

  1. 是LAST_INSERT_ID()來獲取ID的最佳方式?
  2. 如何正確存儲上次插入的評論行中的數據以便在「INSERT into activities」語句中使用?
  3. 我是否應該使用存儲過程的組合以及觸發器?
  4. 觸發器的基本結構是什麼樣的?

謝謝!自從我觸及與數據庫觸發器,程序和函數有關的事情已經有幾​​年了。

回答

36
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) 
+7

對於所有想知道什麼是「新」在這裏是一個代表:_You可以通過使用引用列主題表格(與觸發器關聯的表)別名OLD和NEW。 OLD.col_name在更新或刪除之前引用現有行的列。 NEW.col_name引用要插入的新行的列或更新後的現有行的列._ http://dev.mysql.com/doc/refman/5.0/en///create-trigger.html – SimonSimCity 2013-05-27 09:32:02

相關問題