ALTER TABLE `vn2008`.`department` ADD COLUMN `parentFk` INT UNSIGNED NULL AFTER `sons`, ADD COLUMN `path` VARCHAR(255) NULL AFTER `parentFk`, CHANGE COLUMN `sons` `sons` DECIMAL(10,0) NOT NULL DEFAULT '0' ; USE `vn`; CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = `root`@`%` SQL SECURITY DEFINER VIEW `department` AS SELECT `b`.`department_id` AS `id`, `b`.`name` AS `name`, `b`.`production` AS `isProduction`, `b`.`parentFk` AS `parentFk`, `b`.`path` AS `path`, `b`.`lft` AS `lft`, `b`.`rgt` AS `rgt`, `b`.`isSelected` AS `isSelected`, `b`.`depth` AS `depth`, `b`.`sons` AS `sons` FROM `vn2008`.`department` `b`; DROP TRIGGER IF EXISTS `vn2008`.`department_AFTER_DELETE`; DELIMITER $$ USE `vn2008`$$ CREATE DEFINER = CURRENT_USER TRIGGER `vn2008`.`department_AFTER_DELETE` AFTER DELETE ON `department` FOR EACH ROW BEGIN UPDATE vn.department_recalc SET isChanged = TRUE; END$$ DELIMITER ; DROP TRIGGER IF EXISTS `vn2008`.`department_BEFORE_INSERT`; DELIMITER $$ USE `vn2008`$$ CREATE DEFINER = CURRENT_USER TRIGGER `vn2008`.`department_BEFORE_INSERT` BEFORE INSERT ON `department` FOR EACH ROW BEGIN UPDATE vn.department_recalc SET isChanged = TRUE; END$$ DELIMITER ; DROP TRIGGER IF EXISTS `vn2008`.`department_AFTER_UPDATE`; DELIMITER $$ USE `vn2008`$$ CREATE DEFINER = CURRENT_USER TRIGGER `vn2008`.`department_AFTER_UPDATE` AFTER UPDATE ON `department` FOR EACH ROW BEGIN IF !(OLD.parentFk <=> NEW.parentFk) THEN UPDATE vn.department_recalc SET isChanged = TRUE; END IF; END$$ DELIMITER ; CREATE TABLE `vn`.`department_recalc` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `isChanged` TINYINT(4) NOT NULL, PRIMARY KEY (`id`)); INSERT INTO `vn`.`department_recalc` (`id`, `isChanged`) VALUES ('1', '0'); ALTER TABLE `vn2008`.`department` CHANGE COLUMN `lft` `lft` INT(11) NULL , CHANGE COLUMN `rgt` `rgt` INT(11) NULL ; UPDATE vn.department SET lft = NULL, rgt = NULL;