mysql中触发器 删除表_MySQL触发器:删除后从表中删除

bd96500e110b49cbb3cd949968f18be7.png

Scope: Two tables. When a new patron is created, they have some information about them stored into a 2nd table (This was done using a trigger as well, it works as expected). Here's an example of my table structure and relationship.

Table 1-> patrons

+-----+---------+-----+

+ id + name + val +

+=====+=========+=====+

+ 37 + george + x +

+-----+---------+-----+

+ 38 + sally + y +

+-----+---------+-----+

Table 2 -> patron_info

+----+-----+----------+

+ id + pid + name +

+----+-----+----------+

+ 1 + 37 + george +

+----+-----+----------+

+ 2 + 38 + sally +

+----+-----+----------+

The administrator can manage the patrons. When they choose to remove a patron, the patron is removed from the table 1 patrons. At this point, nothing happens to table 2 patron_info.

I'm simply trying to create a trigger to delete from table 2, when table 1 has an item deleted. Here's what I've tried...

Initially, I try to drop the trigger if it exists (just to clear the air)...

DROP TRIGGER IF EXISTS log_patron_delete;

Then I try to create the trigger afterwards...

CREATE TRIGGER log_patron_delete AFTER DELETE on patrons

FOR EACH ROW

BEGIN

DELETE FROM patron_info

WHERE patron_info.pid = patrons.id

END

At this point, I get a syntax error 1046: Check syntax near END on line 6. I don't know what the error is at this point. I've tried several different variations. Also, am I required to use a delimiter here?

Can anyone help restore my sanity?

解决方案

I think there is an error in the trigger code.

As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)

Try this as the new trigger:

CREATE TRIGGER log_patron_delete AFTER DELETE on patrons

FOR EACH ROW

BEGIN

DELETE FROM patron_info

WHERE patron_info.pid = old.id;

END

Dont forget the ";" on the delete query.

Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值