如何使用AFTER INSERT触发MySQL更新行?

时间:2019-01-10 08:41:41

标签: mysql triggers hierarchy

我有一个表“分支”,反映了层次结构。我希望在插入新行之后为字段“路径”自动分配一个值。 值应形成如下: 选择行的路径,其中id =新插入行的parent_branch_id。例如-对于主分支路径应为'/ 0 /',对于子分支1-'/ 0 // 1 /','/ 0 // 1 // 2 /'等。 如何使用AFTER INSERT触发器MySQL来实现它?

+----+----------------+---------+------+------------------+
| id | name           | address | path | parent_branch_id |
+----+----------------+---------+------+------------------+
|  1 | main branch    | addres1 | NULL |             NULL |
|  2 | sub-branch1    | addres2 | NULL |                1 |
|  3 | sub-sub-branch | addres3 | NULL |                2 |
+----+----------------+---------+------+------------------+

我尝试过这个,

DELIMITER //
CREATE TRIGGER BRANCHES_AFTER_INSERT AFTER INSERT ON branches
FOR EACH ROW
BEGIN
     DECLARE vPath varchar(255);
     DECLARE 
     SET @vPath :=(select path from branches where id = NEW.parent_branch_id);
     UPDATE branches SET  path := @vPath + '/' + NEW.id + '/' ;
END;
//
DELIMITER ;

但是我得到了:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your 
MySQL server version for the right syntax to use near 'SET @vPath :=(select path from center where id = NEW.parent_center_id);
UPDATE' at line 6

0 个答案:

没有答案