Home > Database > Mysql Tutorial > body text

MySQL trigger to insert rows into another table?

PHPz
Release: 2023-08-24 17:53:02
forward
1325 people have browsed it

MySQL trigger to insert rows into another table?

Let us first create a table. CREATE command is used to create a table.

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

Now let's create another table.

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

Now, here's how to create a trigger.

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 ;
Copy after login

To create a trigger we need to change the delimiter.

Inserting a row into table 1 activates the trigger and inserts the record into table 2. Insert records in 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
Copy after login

Check whether records are inserted into both tables.

mysql> select *from Table1;
Copy after login

This is the output showing successful insertion of records in Table1.

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

Check the second table.

mysql>  select *from Table2;
Copy after login

The following is the output showing successful insertion of records in Table2.

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

The above is the detailed content of MySQL trigger to insert rows into another table?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!