我在写触发器的update语句时,需要先查询表的数据是否存在并返回一个值,然后通过判断这个值来决定update的修改条件。代码如下:
delimiter //
CREATE TRIGGER counselor_after_update
AFTER UPDATE
ON `y`.`counselor`
FOR EACH ROW
BEGIN
UPDATE `x`.`t_staff`
SET
`name` = NEW.counselor_name,
`mobile` = NEW.counselor_phone,
`state` = NEW.state
WHERE
IF(select mobile from `x`.`t_staff` where `create_date_time`=OLD.update_time)!=null,mobile = OLD.counselor_phone, create_date_time = OLD.update_time);
END;
//
创建这个触发器是报错了:
You can't specify target table 't_staff' for update in FROM clause
解决方法
将update的修改条件的查询语句更改一下,将现在的查询当成派生表来查询,如下:
原:select mobile from `x`.`t_staff` where `create_date_time`=OLD.update_time
改后:select t.mobile from (select mobile from `x`.`t_staff` where `create_date_time`=OLD.update_time) t
注意:这里的派生表其实就是子查询,外层的查询需要将派生表取别名,我这里取t