32

テーブルに MySQL トリガーを作成しようとしています。基本的に、私はアクティビティ ストリームを作成しており、ユーザーによるアクションをログに記録する必要があります。ユーザーがコメントを作成すると、そのテーブルでデータベース トリガーが起動し、次のようになります。

  1. 最後に挿入された行の ID (コメント行の ID) を取得します。
  2. 最後に挿入された行のデータを使用して、アクティビティ テーブルに INSERT を実行します。

基本的に、コメントを削除するためにこのトリガーを複製します。

私が持っていた質問:

  1. LAST_INSERT_ID() は ID を取得する最良の方法ですか?
  2. 「INSERT into activities」ステートメントで使用するために、最後に挿入されたコメント行のデータを適切に保存するにはどうすればよいですか?
  3. ストアド プロシージャとトリガーを組み合わせて使用​​する必要がありますか?
  4. トリガーの基本構造はどのようになりますか?

ありがとう!DB のトリガー、プロシージャ、および関数に関係するものに触れてから数年が経ちました。

4

1 に答える 1

47
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)
于 2011-01-21T00:49:12.953 に答える