MySQL Trigger After Deleted Update不工作

tez616oj  于 2023-04-19  发布在  Mysql
关注(0)|答案(1)|浏览(91)

我很抱歉再次提出这个问题,因为在论坛上有这么多关于这个的。但我希望我的问题是不同于其他人。对不起,我的英语不好。
首先我有2个表(父和子)父(位置)
| 锁定ID|位置大小|
| --------------|--------------|
| 1|一百|
| 二|七十五|
儿童(地区)
| 干旱|ar_loc_id|ar大小|
| --------------|--------------|--------------|
| 1|二|三十五|
| 二|二|四十|
这是我的after delete触发器。

CREATE TRIGGER after_delete_area_location
AFTER DELETE
   ON area FOR EACH ROW

BEGIN

UPDATE location SET loc_size = loc_size + old.ar_size WHERE loc_id=old.ar_loc_id

END;

例如,如果我想删除ar_id = '2',则ar_size将在位置loc_size中更新。
由于loc_size值为“0”,因此在触发器运行之后,该值将为40。
问题是触发器没有正确运行,loc_size在触发器运行后根本没有更新,只是'0'值。
我错过了什么,或者发生了什么,因为它根本不工作。
请好心地帮助我解决这个问题。非常感谢你提前。

ni65a41a

ni65a41a1#

我看到你的触发器没有问题。我测试了它,它正在工作。为了使它完整,我在表area上添加了插入触发器。

create table location(loc_id int,loc_size int);
create table area(ar_id int,ar_loc_id int,ar_size int);

delimiter //

CREATE TRIGGER after_insert_area_location
AFTER insert
   ON area FOR EACH ROW

BEGIN

UPDATE location SET loc_size = loc_size - new.ar_size WHERE loc_id=new.ar_loc_id;
-- Note: In reality, you should throw in an if statement before the UPDATE to make sure there is enough loca_size to be taken away by the ar_size.
END//

CREATE TRIGGER after_delete_area_location
AFTER DELETE
   ON area FOR EACH ROW

BEGIN

UPDATE location SET loc_size = loc_size + old.ar_size WHERE loc_id=old.ar_loc_id;

END//
delimiter ;

insert into location values(1,100),(2,75);

select * from location;
+--------+----------+
| loc_id | loc_size |
+--------+----------+
|      1 |      100 |
|      2 |       75 |
+--------+----------+

select * from area;
Empty set (0.00 sec)

-- Test the insert
insert into area values(1,2,35),(2,2,40);
select * from area;
+-------+-----------+---------+
| ar_id | ar_loc_id | ar_size |
+-------+-----------+---------+
|     1 |         2 |      35 |
|     2 |         2 |      40 |
+-------+-----------+---------+

 select * from location;
+--------+----------+
| loc_id | loc_size |
+--------+----------+
|      1 |      100 |
|      2 |        0 |
+--------+----------+

-- test the delete
delete from area where ar_id=2;

select * from area;
+-------+-----------+---------+
| ar_id | ar_loc_id | ar_size |
+-------+-----------+---------+
|     1 |         2 |      35 |
+-------+-----------+---------+

select * from location;
+--------+----------+
| loc_id | loc_size |
+--------+----------+
|      1 |      100 |
|      2 |       40 |
+--------+----------+

正如您所看到的,在插入和删除操作中,值都相应地进行了更新。

相关问题