0

所以,我有一个表,通过下面给出的 SQL 描述

CREATE TABLE IF NOT EXISTS `employees` (
`e_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`e_username` varchar(100) NOT NULL,
`left_id` int(10) unsigned NOT NULL,
`right_id` int(10) unsigned NOT NULL,
`e_ssn` int(5) unsigned NOT NULL DEFAULT '0',
`e_first_name` varchar(100) NOT NULL,
`e_last_name` varchar(100) NOT NULL,
`e_address` text NOT NULL,
`e_location` int(10) unsigned DEFAULT NULL,
UNIQUE KEY `e_id` (`e_id`),
UNIQUE KEY `e_username` (`e_username`)
)

它有给定的数据

INSERT INTO `employees` (`e_id`, `e_username`, `left_id`, `right_id`, `e_ssn`, `e_first_name`, `e_last_name`, `e_address`, `e_location`) VALUES
(1, '100884', 1, 8, 444444444, 'James', 'Burnbridge', '1123 fdkjfjdkfjdfkjd', 76),
(2, '100885', 2, 7, 0, 'Frank', 'Grimsley', '123 Fayke St', 76),
(5, '100886', 3, 4, 0, 'Mark', 'Hill', 'kfjdkfjdf\r\nkofjdkfjdkfdj', 76),
(6, '100887', 5, 6, 0, 'fdfdfd', 'fdfdfd', 'fdfdfdf', 76);

我想创建一个触发器,这样当我输入新行时,就像这样

INSERT INTO employees(e_username,left_id,right_id,e_ssn, e_first_name, e_last_name, e_address, e_location)
VALUES('100888', 0, 0, 0, 'New','User', '100 NotReal st city, state zip', 76)

我希望 left_id 和 right_id 列根据其所在位置的第一个用户的 right_id 进行更新,该用户的 right_id 与 left_id 相差 1。

这是我到目前为止所拥有的,但它给了我一个错误

DROP TRIGGER IF EXISTS  `after_insert_employees` ;

CREATE DEFINER =  `root`@`localhost` TRIGGER `after_insert_employees` AFTER INSERT ON  `employees` 
FOR EACH
ROW BEGIN 
DECLARE r_id INT;
SELECT max(right_id) INTO r_id FROM employees WHERE e_location=new.e_location AND right_id = left_id+1;
UPDATE employees SET left_id = r_id+1 AND right_id = r_id+2 WHERE e_id = new.e_id;
END

当我尝试插入某些东西时出现此错误

 #1442 - Can't update table 'employees' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.  

我迷路了。有什么帮助吗?

4

1 回答 1

0

您的触发器将尝试更新您插入的同一个表。MySQL 将在插入发生时锁定表。

此链接可能对您有所帮助

MySql 错误:无法更新存储函数/触发器中的表,因为它已被调用此存储函数/触发器的语句使用

于 2013-09-28T06:28:27.097 回答