所以,我有一个表,通过下面给出的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.
我迷失了这个。有什么帮助吗?
答案 0 :(得分:0)
您的触发器将尝试更新您要插入的同一个表。当插入发生时,MySQL将锁定表。
此链接可以帮助您