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)
Now let's create another table.
mysql> create table Table2 -> ( -> id int, -> name varchar(100) -> ); Query OK, 0 rows affected (0.49 sec)
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 ;
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
Check whether records are inserted into both tables.
mysql> select *from Table1;
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)
Check the second table.
mysql> select *from Table2;
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)
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!