我试图用parentId做Closure表,所以我有两个表(Subjects和SubjectsTree)。当我在Subjects中插入记录时,我需要在SubjectsTree中为每个Subjects.Id = new.ParentId添加记录。我试着这样做:
delimiter //
CREATE TRIGGER test AFTER INSERT ON Subjects
FOR EACH ROW
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE ids INT;
DECLARE cur CURSOR FOR SELECT Id FROM Subjects inner join SubjectsTree on SubjectsTree.DescendantId = new.ParentId;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
ins_loop: LOOP
FETCH cur INTO ids;
IF done THEN
LEAVE ins_loop;
END IF;
INSERT INTO SubjectsTree VALUES (ids, new.Id);
END LOOP;
CLOSE cur;
insert into SubjectsTree values (new.Id, new.Id);
END; //
但它不起作用只是因为它重复了主题中的所有记录!当我尝试没有循环时,它没有。
为什么不对主题中的每条记录执行此代码?
在主题上插入后创建触发器测试 对于每一行 插入some_test_table值('测试值');
我该如何解决这个问题?或者也许有更好的方法?
Subjects table:
Id int PRI
Name longtext
ParentId int
SubjectsTree table:
AncestorId int PRI
DescendantId int PRI
答案 0 :(得分:0)
更容易解决这个问题。
drop trigger if exists test;
create trigger test after insert on Subjects
for each row
insert into SubjectsTree select AncestorId, new.Id, 1 from SubjectsTree
where DescendantId = new.ParentId union all select new.Id, new.Id, 1;