MySQL触发器将行插入另一个表?

数据库数据库 2023-08-31 03:34:04 795
摘要: 让我们首先创建一个表。CREATE命令用于创建表。mysql>createtableTable1->(->idint,->namevarchar(100)->);QueryOK,0rowsaffected(0.62sec)现在让我们创建另一个表。mysql>...

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 ;

要创建触发器,我们需要更改分隔符。

将行插入表 1 会激活触发器并将记录插入表 2。在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)

以上就是MySQL触发器将行插入另一个表?的详细内容,更多请关注其它相关文章!