我有2个表member_details
和archives
。我想要trigger
insert
,只要从member_details
表中删除特定记录,就会archives
将数据从member_details
删除到DELIMITER $$
CREATE TRIGGER member_details_ADEL AFTER DELETE ON member_details
FOR EACH ROW
insert into archives values
。
{{1}}
答案 0 :(得分:0)
您可以使用OLD
关键字从已删除的记录中获取值
但是您必须使用insert
语句指定列名。
示例:
delimiter //
drop trigger if exists member_details_adel //
create trigger member_details_adel
after delete on member_details
for each row
insert
into archives( col1, col2, colx )
values( old.col1, old.col2, old.colx );
//
delimiter ;
根据您的表格需要更改和扩展列名称。
更新1 :
您尝试过的触发器主体中存在语法错误 更正了一个如下:
delimiter $$
create trigger member_details_adel
after delete on member_details
for each row
insert
into archives (title, name, name of spouse,
level of education, address,
phone number, occupation,
date joined, emergency contact)
values (old.title, old.name, old.`name of spouse`,
old.`level of education`, old.`address`,
old.`phone number`, old.`occupation`,
old.`date joined`, old.`emergency contact`);
$$
delimiter ;
答案 1 :(得分:0)
这是你可以做到的,假设你有一个名为test的表,其中包含以下数据
mysql> select * from test ;
+----------------------+
| id |
+----------------------+
| 10 |
| 20 |
| 30 |
+----------------------+
您有另一个名为test1的表,因为当前没有数据
mysql> select * from test1 ;
Empty set (0.00 sec)
现在让我们编写一个触发器,这样当测试表上有删除时,删除的记录会被添加到test1表中。您需要使用after delete
触发器,并使用old.col
获取数据
在这个示例中,我只有一列您可以使用old.col名称来访问执行触发器的表上的任何列
delimiter //
create trigger log_delete after delete on test
for each row
begin
insert into test1 (id) values (old.id);
end ; //
delimiter ;
现在让我们将测试表中的记录删除为
mysql> delete from test where id = 10 ;
Query OK, 1 row affected, (0.00 sec)
mysql> select * from test ;
+----------------------+
| id |
+----------------------+
| 20 |
| 30 |
+----------------------+
2 rows in set (0.00 sec)
mysql> select * from test1 ;
+----------------------+
| id |
+----------------------+
| 10 |
+----------------------+
1 row in set (0.00 sec)
现在您可以看到删除的行已添加到表test1。
您需要做的就是在上面的触发器中设置正确的表名和列名以及您想要的触发器名称
USE church;
DELIMITER $$
CREATE TRIGGER member_details_ADEL AFTER DELETE ON member_details
FOR EACH ROW
begin
insert into archives
(TITLE, NAME, `NAME OF SPOUSE`, `LEVEL OF EDUCATION`, ADDRESS, `PHONE NUMBER`, OCCUPATION, `DATE JOINED`, `EMERGENCY CONTACT`)
values
(old.TITLE, old.NAME, old.`NAME OF SPOUSE`, old.`LEVEL OF EDUCATION`, old.`ADDRESS`, old.`PHONE NUMBER`,old.`OCCUPATION`, old.`DATE JOINED`, old.`EMERGENCY CONTACT`);
END ; $$
delimiter ;
当存在空格或使用reserve关键字时,请确保对列名称进行反引号。