使用MySQL 觸發器將行插入另一個表
在MySQL 等關係資料庫管理系統中,觸發器在自動化某些資料庫操作方面發揮關鍵作用響應特定事件,例如資料插入、刪除或修改。在這種情況下,讓我們深入研究創建觸發器的主題,該觸發器在給定表中插入行時將行插入到另一個表中。
理解問題
The目標是在「comments」表上建立一個 MySQL 觸發器來監視每一行插入事件。當插入新的註解行時,觸發器應執行以下任務:
觸發器結構
實現這些功能的觸發器的基本結構涉及以下內容:
CREATE TRIGGER <trigger_name> AFTER INSERT ON <source_table> FOR EACH ROW BEGIN -- Retrieve the ID of the newly inserted row DECLARE last_insert_id INT; SET last_insert_id = LAST_INSERT_ID(); -- Insert data into the "activities" table INSERT INTO <target_table> (column_list) VALUES (new.column1, new.column2, ..., last_insert_id); END
觸發器實作
用於演示實現,考慮以下示例:
-- Create the "comments" and "activities" tables CREATE TABLE comments ( comment_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, user_id INT UNSIGNED NOT NULL ) ENGINE=INNODB; 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; -- Create the trigger to insert data into the "activities" table CREATE TRIGGER comments_after_ins_trig AFTER INSERT ON comments FOR EACH ROW BEGIN -- Retrieve the ID of the newly inserted comment row DECLARE last_insert_id INT; SET last_insert_id = LAST_INSERT_ID(); -- Insert data into the "activities" table INSERT INTO activities (comment_id, user_id) VALUES (new.comment_id, new.user_id); END; -- Insert some data into the "comments" table INSERT INTO comments (user_id) VALUES (1), (2); -- Query the "comments" and "activities" tables to observe the results SELECT * FROM comments; SELECT * FROM activities;
執行查詢時,您會注意到對於每個評論行插入到“評論”表中,相應的行會自動插入到“活動”表中。這證明了觸發器在實現預期結果方面的有效性。
以上是如何使用 MySQL 觸發器將資料列插入到另一個表中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!