將行插入另一個表的 MySQL 觸發器?


讓我們首先建立一個表。CREATE 命令用於建立表。

mysql> create table Table1
   -> (
   -> id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.62 sec)

現在,讓我們建立一個新表。

mysql> create table Table2
   -> (
   -> id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.49 sec)

以下是建立觸發器的方法。

mysql> delimiter #
mysql> create trigger Table1Trigger after insert on Table1
   -> for each row
   -> begin
   ->  insert into Table2(id, name) values (new.id, new.name);
   -> end#
Query OK, 0 rows affected (0.29 sec)

mysql> delimiter ;

要建立觸發器,我們需要更改分隔符。

將行插入 Table1 會啟用觸發器,並將記錄插入 Table2。要在 Table1 中插入記錄。

mysql> insert into Table1 values(1,'John'),(2,'Smith'),(3,'Carol');
Query OK, 3 rows affected (0.28 sec)
Records: 3  Duplicates: 0  Warnings: 0

檢查記錄是否插入到兩個表中。

mysql> select *from Table1;

以下是輸出,顯示成功將記錄插入 Table1。

+------+-------+
| id   | name  |
+------+-------+
|    1 | John  |
|    2 | Smith |
|    3 | Carol |
+------+-------+
3 rows in set (0.00 sec)

檢查第二個表。

mysql>  select *from Table2;

以下是輸出,顯示成功將記錄插入 Table2。

+------+-------+
| id   | name  |
+------+-------+
|    1 | John  |
|    2 | Smith |
|    3 | Carol |
+------+-------+
3 rows in set (0.00 sec)

更新時間:30-7-2019

13K+ 瀏覽量

開啟你的 職業

完成課程並獲得認證

開始
廣告
© . All rights reserved.