sql >> Base de Datos >  >> RDS >> Mysql

mysql - Insertar fila en la tabla 1 cuando se elimina una fila específica en la tabla 2

Considere el siguiente ejemplo y cambie de acuerdo con su disparador

mysql> create table test (id int, val varchar(20),date datetime);
Query OK, 0 rows affected (0.09 sec)

mysql> insert into test values (1,'aa',now()),(2,'bb',now()),(3,'cc',now());
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> create table test1 like test;
Query OK, 0 rows affected (0.06 sec)

mysql> delimiter //
mysql> create trigger test_del after delete on test 
    -> for each row
    -> begin
    -> insert into test1 (id,val,date) values (old.id,old.val,old.date);
    -> end ;
    -> //
Query OK, 0 rows affected (0.12 sec)

mysql> delimiter ;
mysql> select * from test ;
+------+------+---------------------+
| id   | val  | date                |
+------+------+---------------------+
|    1 | aa   | 2014-09-15 15:08:13 |
|    2 | bb   | 2014-09-15 15:08:13 |
|    3 | cc   | 2014-09-15 15:08:13 |
+------+------+---------------------+
3 rows in set (0.01 sec)

mysql> select * from test1;
Empty set (0.00 sec)

mysql> delete from test where id = 1 ;
Query OK, 1 row affected (0.03 sec)

mysql> select * from test1 ;
+------+------+---------------------+
| id   | val  | date                |
+------+------+---------------------+
|    1 | aa   | 2014-09-15 15:08:13 |
+------+------+---------------------+
1 row in set (0.00 sec)